VBA If..Not (Logical Operator): Explained with 2 Examples
Basically, Not operator negates the given condition. It is used to reverse the result of a condition or expression.
Purpose of VBA If Not – Logical operator
Just like the VBA “And” and “Or” operators, the “Not” is a logical operator that we use in the If..Statement.
- The code inside If..And execute as all conditions are True.
- In case of If..Or, if any of the given conditions is True, the code inside If executes.
- The Code executes in the If..Not case, if a given condition is False.
- Basically, Not operator negates the given condition. It is used to reverse the result of a condition or expression.
- The examples below should make it clearer.
An example of Not operator
See the following example and its output:
Code with If..Not:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Sub if_not_demo() Dim x As Integer x = 10 If Not x = 10 Then MsgBox "Code in If..Not statement executed!" Else MsgBox "Code in Else statement executed" End If End Sub |
Result:
If we omit “Not” in the If..then statement:
If x = 10 Then
Code in the If statement executes.
As we used “Not” in our program, it negated the result – so the Else code executed.
Using Excel Cell to demonstrate Not operator further
Let us use the if..Not operator with Excel cell.
We will set the cell interior color based on the condition with the Not operator.
If the current color of the A1 cell is Red, the C3 cell will be set to Green
If not Red, it should be set to Yellow.
See the code and output below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
Sub if_not_demo() Dim x As Integer, color1 'Getting the color of A1 cell color1 = Range("A1").Interior.ColorIndex 'Color value 3 = Red. 6 = Yellow. 10 = Green If Not color1 = 3 Then Range("C1").Interior.ColorIndex = 6 Else Range("C1").Interior.ColorIndex = 10 End If End Sub |
Result:
As the color of the A1 cell is Red (3), and it negates the “Not” condition, so Else part was executed and it made the color of C3 cell green.