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’s 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:
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."
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.
If Not ActiveSheet.Name = Sheets("Sheet1").Name Then
Now, in this code, you have used NOT with IF to see if the active sheet is Sheet1 or not, and if it is not, the line of code that we have specified will activate Sheet1.