Question

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.

Was it helpful?

Solution

The default property of a range object is .Value so when you say If Target = rTime.Offset(0, 1), it will always compare the values in that range rather than the address of those ranges.

One way is already shown by L42. Here is another way using Intersect

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

EDIT

When you say Target.Column and Target.Row, you will always get the first column and the first row of the cell in that range, even if Target has multiple cells. To avoid this use the below to ensure that you have the desired Target. Your code will give you unexpected results even if there is a single cell in Target. For example, say the value of cell B1 is equal to any other cell which at the moment is target. So if Cell B1 = "Sid" and Cell F1 = "Sid" and you select cell F1 then you will get the "Hello World" message box.

For xl2003, you can use an additional check

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

For xl2007+, replace Target.Cells.Count with Target.Cells.CountLarge

For L42

Your method is correct but then you also will have to put the above check to get the correct results.

OTHER TIPS

try this:

Edit1: To cover Chis' concern

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

you cannot compare objects, just the properties? I'm not certain though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top