VBA IF OR (Test Multiple Conditions)

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

- Written by Puneet

You can use the OR operator with the VBA IF statement to test multiple conditions. When you use it, it allows you to test two or more conditions simultaneously and returns true if any of those conditions are true. But if all the conditions are false only then it returns false in the result.

Use OR with IF

  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 OR keyword to specify the second condition.
  4. In the end, specify the second condition that you want to test.
vba-if-or-condition

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

Sub myMacro()

'two conditions to test using OR
If 1 = 1 Or 2 < 1 Then
    MsgBox "One of the conditions is true."
Else
    MsgBox "None 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 only the first condition is true, and even though it has executed the line of code that we have specified if the result is true.

Now let’s see if both conditions are false, let me use a different code here.

Sub myMacro()

'two conditions to test using OR
If 1 = 2 Or 2 < 1 Then
    MsgBox "One of the conditions is true."
Else
    MsgBox "None of the conditions are true."
End If

End Sub

In the above code, both conditions are false, and when you run this code, it executes the line of code that we have specified if the result is false.

Multiple Conditions with IF OR

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 myMacro()

'three conditions to test using OR

If 1 = 1 And 2 > 1 And 1 - 1 = 0 Then
    MsgBox "one of the conditions is true."
Else
    MsgBox "none of the conditions are true."
End If

End Sub

Now we have three conditions to test, and we have used the OR after the second condition to specify the third condition. As you learned above that when you use OR, any of 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 all the conditions are false, just like you have in the following code, it returns false.

Sub myMacro()

'three conditions to test using OR
If 1 < 1 And 2 < 1 And 1 + 1 = 0 Then

    MsgBox "one of the conditions is true."

Else

    MsgBox "none of the conditions are true."

End If

End Sub