VBA: Use IF OR to Test Multiple Conditions


You can use the following basic syntax in VBA with IF and OR to test if multiple conditions are met:

Sub IfOrTest()
    If Range("A2") = "Warriors" Or Range("B2") > 100 Then
    Range("C2").Value = "Yes!"
    Else
    Range("C2").Value = "No."
    End If
End Sub

This particular example checks if the value in cell A2 is equal to “Warriors” or if the value in cell B2 is greater than 100.

If either condition is met, a value of “Yes!” is returned in cell C2.

Otherwise, a value of “No.” is returned in cell C2.

The following example shows how to use this syntax in practice.

Related: VBA: Use IF AND to Test Multiple Conditions

Example: Use IF AND to Test Multiple Conditions in VBA

Suppose we have the following data in Excel:

Suppose we would like to determine if the team name is Warriors or if the points value is greater than 100 and return the result in cell C2.

We can create the following macro to do so:

Sub IfOrTest()
    If Range("A2") = "Warriors" Or Range("B2") > 100 Then
    Range("C2").Value = "Yes!"
    Else
    Range("C2").Value = "No."
    End If
End Sub

When we run this macro, we receive the following output:

The macro correctly returns a value of “Yes!” in cell C2 since at least one of the conditions were met.

If we change the value of the points in cell A2 and then run the macro again, it will test if both conditions are met for the new values:

For example, suppose we change the team name to “Rockets” and run the macro again:

The macro correctly returns a value of “No.” in cell C2 since neither condition was met.

If you would instead like to display the results in a message box, you can use the following syntax:

Sub IfOrTest()
    If Range("A2") = "Warriors" Or Range("B2") > 100 Then
    MsgBox "Yes!"
    Else
    MsgBox "No."
    End If
End Sub

When we run this macro, we receive the following output:

The message box returns “No.” since neither condition was met.

Note: In this example, we only used the Or operator once in our macro to test if two conditions were met but you can use as many Or operators as you’d like to test if more than two conditions are met.

Additional Resources

The following tutorials explain how to perform other common tasks in VBA:

VBA: How to Use VLOOKUP
VBA: How to Count Occurrences of Character in String
VBA: How to Check if String Contains Another String

Leave a Reply

Your email address will not be published. Required fields are marked *