How do I use VBA with IF AND to test multiple conditions?

VBA with IF AND can be used to test multiple conditions at once. This is done by nesting multiple IF statements together, each with its own condition. The VBA code will evaluate each condition sequentially and execute the corresponding action for each one that is met. This makes it easier to set up a complex decision-making process without having to write out each individual IF statement.


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

Sub IfAnd()
    If Range("A2") = "Warriors" And 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” and if the value in cell B2 is greater than 100.

If both conditions are 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.

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 and 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 IfAnd()
    If Range("A2") = "Warriors" And 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 “No.” in cell C2 since both conditions weren’t met.

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

For example, suppose we change the points value to 104 and run the macro again:

The macro correctly returns a value of “Yes!” in cell C2 since both conditions were met.

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

Sub IfAnd()
    If Range("A2") = "Warriors" And 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 “Yes!” since the team name is Warriors and the points value is greater than 100.

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

x