VBA IF And (Test Multiple Conditions)

Last Updated: June 22, 2023
puneet-gogia-excel-champs

- Written by Puneet

You can use the AND operator with the VBA IF statement to test multiple conditions, and when you use it allows you to test two conditions simultaneously and get true if both of those conditions are true. And, if any of the conditions is false it returns false in the result.

Combining IF AND

  1. First, start the IF statement with the “IF” keyword.
  2. After that, specify the first condition that you want to test.
  3. Next, use the AND keyword to specify the second condition
  4. In the end, specify the second condition that you want to test.
vba-if-statement

To have a better understanding let’s see an example.

Sub myMacro()
If 1 = 1 And 2 > 1 Then
    MsgBox "Both of the conditions are true."
Else
    MsgBox "Maybe one or both of the conditions are true."
End If
End Sub

If you look at the above example, we have specified two conditions one if (1 = 1) and the second is (2 > 1) and here both of the conditions are true, and that’s why it executes the line of code that we have specified if the result is true.

Now lets if one of these two conditions is false, let me use a different code here.

Sub myMacro1()

If 1 = 1 And 2 < 1 Then

    MsgBox "Both of the conditions are true."

Else

    MsgBox "Maybe one or both of the conditions are true."

End If

End Sub

In the above code, the second condition is false (2 < 1) and when you run this macro it executes the line of code that we have specified if the result is false.

Multiple Conditions with IF AND

In the same way, you can also test more than two conditions at the same time. Let’s continue the above example and add the third condition to it.

Sub myMacro2()

If 1 = 1 And 2 > 1 And 1 - 1 = 0 Then

    MsgBox "All the conditions are true."

Else

    MsgBox "Some conditions are false."

End If

End Sub

Now we have three conditions to test and we have used the AND after the second condition to specify the third condition. As you learned above that when you use AND, all the conditions need to be true to get true in the result.

When you run this code, it executes the line of code that we have specified for the true.

And if any of the conditions is false, just like you have in the following code, it returns false.

Sub myMacro3()

If 1 = 1 And 2 < 1 And 1 + 1 = 0 Then

    MsgBox "All the conditions are true."

Else

    MsgBox "Some conditions are false."

End If

End Sub