jeudi 24 juin 2021

VBA IF ... AND ... Statement returns no results?

I have a macro which searches a table according to two user inputs, with both conditions needing to match. For some reason, the search works fine when omitting the second condition but not with it.

This doesn't work.

For Each Cell1 In Sheet1.Range("A2:D1000")
    If Cell1.Value = SearchCondition1 And Cell1.Offset(0, 3).Value = SearchCondition2 Then
        DoSomething
    ElseIf
        MsgBox("Nothing was found")
    End If
Next

This does

For Each Cell1 In Sheet1.Range("A2:D1000")
    If Cell1.Value = SearchCondition1 Then
        MsgBox ("row 4 value = " & Cell1.Offset(0, 3).Value)
'This prints the value that I was trying to check, but for some reason will not check it as a condition.
        DoSomething
    ElseIf
        MsgBox("Nothing was found")
    End If
Next

I have to assume I'm making a really simple mistake, when I run the first example it will run without error and pretend that nothing in the table matches both conditions. When I run the second example, it finds many results and will even print the value I'm trying to check against.

Aucun commentaire:

Enregistrer un commentaire