3

I run into this issue a fair amount and am curious if someone can tell me why or how I can write this a little cleaner.

Below is my code and it does work.

If Target.Row = rTime.Offset(0, 1).Row Then
    If Target.Column = rTime.Offset(0, 1).Column Then
        cboStatus.Activate
    End If
End If

How come I can’t just write it like this?

If Target = rTime.Offset(0, 1) Then
    cboStatus.Activate
End If

If target is already a range then why do I need to specify the individual row and individual column? That second code will not work and I have tried many variations of it. I even tried something like If Target.Range = range(“C4”) Then or If Target.Range = cells(4, 3) Then, but neither of those worked either. I tried many variations of similar stuff. Although, I don’t want to use a specific range like A4, since I wanted to use the rTime like what is in the example, but I was just trying to figure this out.

Nothing seems to work, other than specifying the individual row and column each time. Can someone please explain this to me? Also, is there a better way to write this than what I did in the first example, which does work?

Thanks for anything that relieves my confusion.

4

2 回答 2

4

范围对象的默认属性是.Value,当您说 时If Target = rTime.Offset(0, 1),它将始终比较该范围内的值,而不是这些范围的地址。

L42 已经展示了一种方法。这是另一种使用方式Intersect

If Not Intersect(Target, rtime.Offset(0, 1)) Is Nothing Then cboStatus.Activate

编辑

当您说Target.ColumnandTarget.Row时,您将始终获得该范围内单元格的第一列和第一行,即使Target有多个单元格也是如此。为避免这种情况,请使用以下内容以确保您拥有所需的Target. 即使Target. 例如,假设单元格的值B1等于当前为 的任何其他单元格target。因此,如果 Cell B1= "Sid" 和 Cell F1= "Sid" 并且您选择了单元格F1,那么您将看到“Hello World”消息框。

对于 xl2003,您可以使用附加检查

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim rtime As Range

    Set rtime = Range("A1")

    If Target.Cells.Count > 1 Then
        MsgBox "you have chosen more than one cell"
        Exit Sub
    End If

    If Not Intersect(Target, rtime.Offset(0, 1)) Is Nothing Then
        MsgBox "Hello World"
    End If
End Sub

对于 xl2007+,替换Target.Cells.CountTarget.Cells.CountLarge

对于 L42

您的方法是正确的,但是您还必须进行上述检查才能获得正确的结果。

于 2013-11-11T07:50:51.497 回答
2

尝试这个:

Edit1:为了掩盖 Chis 的担忧

If Target.Address = rtime.Offset(0,1).Address(,,,True) then cboStatus.Activate

你不能比较对象,只能比较属性?不过我不确定。

于 2013-11-11T07:32:08.127 回答