HomeVBA TutorialVBA IF Not

In VBA, when you use the IF statement, it executes a line of code if the condition you have specified to test is TRUE. But when you use the NOT operator with IF, it checks if the condition you have specified is not TRUE and executes the code based on that. It’s like making the IF statement opposite, TRUE into FALSE and FALSE into TRUE.

Let say you want to test if A < B, and if this condition is true IF will return TRUE, right? But when you use IF NOT A < B, it will return FALSE.

Note: NOT is a logical operator.

Examples to use VBA IF NOT

Here’s we will see a simple example to understand it:

Sub myMacro()

Dim A As Range, B As Range
Set A = Range("A1")
Set B = Range("B1")

If Not A < B Then
    MsgBox "A is not greater than B."
    MsgBox "B is not greater than A."
End If
End Sub

In the above code, you have used the NOT operator to test whether B is not greater than the A.

If you look at the condition statement, you can understand the actual condition to test is if B is greater than A, but as we have used the NOT statement, it will return FALSE if the condition is TRUE.

Here’s another example that you can use to understand it.

Sub myMacro()

If Not ActiveSheet.Name = Sheets("Sheet1").Name Then
End If

End Sub

Now, in this code, you have used NOT with IF to see the if the activesheet is Sheet1 or not, and if it is not, the line of code that we have specified will activate the Sheet1.

There’s More

Below are some of the links which could be useful for you and if you want to learn more about VBA, check out this Excel VBA Tutorial – The Best Way to Learn Programming in Excel.

VBA Nested IF | VBA IF And | VBA IF Or | VBA Exit IF