How to use Not Equal Operator in VBA in Excel (Code)

puneet-gogia-excel-champs

- Written by Puneet

In VBA, just like Excel, you can use the Not Equal operator to test a condition. The not equal operator combines greater than and less than operators. And it returns a Boolean value (TRUE and FALSE).

In this tutorial, we are going to learn to use it.

Use Not Equal Operator to Test Two Values

  1. Enter the first value or specify the range where you have the value.
  2. Type the “<” greater than operator using your keyboard.
  3. Now, type “>” less than operator using your keyboard.
  4. In the end, specify the second value.
use-not-equal-operator-in-vba

In the above example, you can see that we have used the not equal operator to test three different conditions.

  • Cell A1 with the cell A2.
  • The value “One” with the value “Two”.
  • The number 1 with 2.

We have used the message box to get the result of the conditions.

Sub not_equal()
MsgBox Range("A1") <> Range("A2")
MsgBox "One" <> "Two"
MsgBox 1 <> 1
End Sub

Using NOT EQUAL with in IF Statement in VBA

The best use case of the not equal operator is with the IF statement. You can see in the example below that we use it with IF to test whether cell A1 has a value.

Sub not_equal()
If Range("A1").Value <> "" Then    
   MsgBox "Yes"
Else    
MsgBox "No"
End If
End Sub
use-not-equal-with-if-in-vba

When you run this code, the IF statement tests if the values in cell A1 are not equal to a blank value. If the statement is true, it shows a message box with “Yes”.

And if there is a value in cell A1, the not equal condition returns a FALSE, and the IF statement shows a message box with “No”.

Last Updated: December 06, 2023