VBA Not Equal Sign: Complete Guide to the <> Operator

Master the VBA not equal sign (<>) with this complete guide. Learn syntax, string comparison, Null handling, and practical Excel examples to fix your macros.

You've written your first IF statement, but your VBA code isn't behaving as expected. The culprit is often a misunderstood not equal sign (<>). It looks simple—just two characters—but the way it behaves with strings, Null values, and floating-point numbers can trip up even experienced developers.

I've spent years debugging Excel macros where the logic seemed bulletproof on paper but fell apart at runtime. In nearly every case, the issue traced back to how the <> operator handled a specific data type or edge case. This guide goes beyond the basic syntax to cover what most quick-reference tutorials miss: the why behind common failures and how to work around them.


Close-up of HTML code lines highlighting web development concepts and techniques.

What is the VBA Not Equal Operator (<>) and How Does It Work?

The not equal sign in VBA is the <> operator—the exact inverse of the = operator. When you compare two values with <>, VBA evaluates whether they are different and returns a Boolean result: True if they're not equal, False if they are.

The Symmetry of = and <>

Think of = and <> as two sides of the same coin. If 10 = 10 returns True, then 10 <> 10 returns False. The logic is perfectly mirrored.

Here's a quick demonstration you can run in the Immediate Window (press Ctrl+G in the VBA editor):

Debug.Print 10 <> 10    ' Returns: False
Debug.Print 10 <> 99    ' Returns: True
Debug.Print "A" <> "B"  ' Returns: True

Each comparison produces a vba boolean expression—either True or False—which you can then use in conditional logic, assign to a variable, or output directly.

Syntax and Placement in Conditional Logic

The standard syntax follows the pattern:

If variable1 <> variable2 Then
    ' Code to execute when they're different
End If

Here's a minimal working example you can paste directly into a module:

Sub CompareCells()
    Dim cellA As String
    Dim cellB As String
    
    cellA = Range("A1").Value
    cellB = Range("B1").Value
    
    If cellA <> cellB Then
        MsgBox "The values are different."
    Else
        MsgBox "The values are the same."
    End If
End Sub

This is the foundation. But here's where things get interesting—and where most people run into trouble.


Close-up of colorful coding text on a dark computer screen, representing software development.

String Comparison with <>: The Critical Role of Option Compare

When comparing strings with <>, the results depend entirely on a module-level setting you might not even know exists: Option Compare. This single line at the top of your module controls whether VBA treats "APPLE" and "apple" as the same or different.

Case Sensitivity: Binary vs. Text Comparison

By default, VBA is case-insensitive. That means "APPLE" <> "apple" returns False—VBA considers them equal. This is because the default setting is Option Compare Text (or the database default, which behaves similarly).

If you need case-sensitive comparisons, you must explicitly declare Option Compare Binary at the top of your module. This forces VBA to compare strings based on their binary representation, making "APPLE" <> "apple" return True.

Here's a comparison table showing how the same expression evaluates under both settings:

ExpressionOption Compare Text (Default)Option Compare Binary
"APPLE" <> "apple"False (they're equal)True (they're different)
"Hello" <> "hello"FalseTrue
"ABC" <> "abc"FalseTrue
The vba option compare setting is module-level, meaning it applies to all code in that module. You can't change it mid-procedure. In my experience, most developers don't realize this setting exists until they encounter a bug where string comparisons behave unexpectedly.

Handling Empty Strings and Spaces

Here's a subtle trap I've seen catch people repeatedly: the difference between an empty string ("") and a string containing only spaces (" ").

Dim emptyStr As String
emptyStr = ""

Dim spaceStr As String
spaceStr = " "

Debug.Print emptyStr <> spaceStr  ' Returns: True

These are not equal. An empty string has zero characters; a string with a space has one character. When you're cleaning imported data, this distinction matters enormously. A cell that looks blank might actually contain spaces, and your <> comparison will treat it as different from a truly empty cell.

The fix is simple: use the Trim function to strip leading and trailing spaces before comparing.

If Trim(Range("A1").Value) <> "" Then
    ' Cell has actual content
End If

Why Your VBA Not Equal Sign Isn't Working: Common Pitfalls

When someone tells me their vba not equal sign isn't working, nine times out of ten, it's one of three issues. Let's tackle each one.

The Null Value Trap

This is the most dangerous pitfall, and it's the one that causes the most confusing bugs. In VBA, any comparison involving Null returns Null—not True, not False, but Null itself.

Dim var As Variant
var = Null

If var <> "something" Then  ' This evaluates to Null, not True
    MsgBox "This won't run reliably"
End If

When Null is used in an If statement, it's treated as False, so your code silently skips the block you expected to execute. This is particularly problematic when reading from database fields or uninitialized variables.

The solution is to explicitly check for Null before using <>:

If Not IsNull(var) Then
    If var <> "something" Then
        MsgBox "Now this works correctly"
    End If
End If

This vba not equal to null handling is essential for robust code. I've seen production macros fail for months because of this exact issue—the developer assumed Null would behave like an empty string, but it doesn't.

Floating-Point Precision and Type Coercion

Here's a surprising result that stumps many developers:

Debug.Print 0.1 + 0.2 <> 0.3  ' Returns: True

Wait, what? 0.1 + 0.2 equals 0.3, right? Not in binary floating-point arithmetic. Computers store numbers in binary, and some decimal fractions can't be represented exactly. The result is a tiny rounding error that makes the comparison return True when you'd expect False.

The workaround is to use a tolerance-based approach:

Dim a As Double
Dim b As Double
a = 0.1 + 0.2
b = 0.3

If Abs(a - b) > 0.0001 Then
    ' They're "different" within our tolerance
Else
    ' They're effectively equal
End If

VBA also attempts to coerce data types during comparison, which can lead to unexpected results. For example, comparing a number to a string that looks like a number:

Debug.Print 100 <> "100"  ' Returns: False (VBA converts the string to a number)

This type coercion is convenient but can mask data quality issues in your spreadsheets.


Practical Excel VBA Examples: Beyond the Basics

Now let's put the <> operator to work in real-world scenarios. These are the kinds of macros I've written countless times for clients.

Looping and Filtering Data with <>

One of the most common uses is looping through a range and identifying cells that don't match a specific value. Here's a complete macro that highlights all cells in column A that aren't equal to "Approved":

Sub HighlightNonApproved()
    Dim lastRow As Long
    Dim i As Long
    Dim targetValue As String
    
    targetValue = "Approved"
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row
    
    For i = 1 To lastRow
        If Cells(i, 1).Value <> targetValue Then
            Cells(i, 1).Interior.Color = RGB(255, 200, 200)  ' Light red
        End If
    Next i
    
    MsgBox "Highlighting complete. " & lastRow & " rows checked."
End Sub

This excel vba if not equal then pattern is the backbone of countless data-cleaning and validation macros.

Comparing Cell Values and Worksheet Names

Another powerful use case is comparing two columns to find discrepancies. Here's a macro that compares column A and column B and flags mismatches:

Sub FindDiscrepancies()
    Dim lastRow As Long
    Dim i As Long
    
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row
    
    For i = 1 To lastRow
        If Cells(i, 1).Value <> Cells(i, 2).Value Then
            Cells(i, 3).Value = "No Match"
            Cells(i, 3).Font.Color = RGB(200, 0, 0)
        Else
            Cells(i, 3).Value = "Match"
            Cells(i, 3).Font.Color = RGB(0, 150, 0)
        End If
    Next i
End Sub

You can also use <> to manage worksheets. This macro hides all sheets except the one you specify:

Sub HideAllExceptMain()
    Dim ws As Worksheet
    
    For Each ws In ThisWorkbook.Worksheets
        If ws.Name <> "MainSheet" Then
            ws.Visible = xlSheetVeryHidden
        End If
    Next ws
End Sub

VBA Not Equal vs. Other Comparison Methods

The <> operator isn't the only way to express inequality in VBA, but it's usually the best one.

The Not Keyword and IsNot (and why it doesn't exist)

If you're coming from VB.NET, you might look for an IsNot operator. It doesn't exist in VBA. You have two alternatives:

' Method 1: The <> operator (preferred)
If a <> b Then

' Method 2: The Not keyword with =
If Not (a = b) Then

Both work, but <> is more readable and idiomatic. The Not approach requires extra parentheses and reads less naturally. In terms of performance, there's no meaningful difference—VBA compiles both to similar operations.

This vba not equal vs isnot distinction is a common source of confusion for developers transitioning from other languages.

When to Use Like Instead of <>

The <> operator checks for exact inequality. But what if you need pattern matching? That's where the vba like operator comes in.

ExpressionResultExplanation
"Hello" <> "H*"True<> does literal comparison
"Hello" Like "H*"TrueLike supports wildcards
"World" Like "H*"FalsePattern doesn't match
Use <> when you need exact inequality. Use Like when you need fuzzy matching—for example, checking if a string doesn't start with a specific prefix:
If name Like "Dr.*" Then
    ' It's a doctor
Else
    ' Not a doctor
End If

Frequently Asked Questions

How do I write "not equal" in VBA?

The not equal operator is written as <>. For example:

If 5 <> 6 Then MsgBox "Not Equal"

It's the direct opposite of the = operator. When the two values are different, <> returns True; when they're the same, it returns False.

Is <> the same as != in VBA?

No. The != operator is not valid in VBA. The correct symbol is <>. The != syntax is used in languages like C# and Python, which can cause confusion for multi-language developers. If you try to use != in VBA, you'll get a compile error.

Why is my not equal operator not working in VBA?

The most common reasons are:

  1. Comparing with Null — Any comparison with Null returns Null, which is treated as False in an If statement. Use IsNull() to check first.
  2. String case sensitivity — By default, VBA is case-insensitive. Use Option Compare Binary for case-sensitive comparisons.
  3. Floating-point precision — Binary representation errors can make mathematically equal values appear different. Use a tolerance-based approach instead.

How to compare two cells for inequality in VBA?

Use a direct comparison of the cell values:

If Range("A1").Value <> Range("B1").Value Then
    MsgBox "The cells are different"
End If

For multiple rows, wrap this in a loop as shown in the earlier examples.


Conclusion

The VBA not equal sign (<>) is a powerful tool, but its behavior is context-dependent. The key takeaways from this guide:

  • Always handle Null values before using <> — this is the #1 source of bugs
  • Be mindful of Option Compare for string comparisons — the default might not match your expectations
  • Watch out for floating-point limitations — use tolerance-based comparisons for decimal arithmetic

Understanding these nuances will make your VBA code more robust and error-free. I've seen these issues cause hours of debugging for developers who assumed <> was as simple as it looks.

If you'd like a ready-to-use VBA code module containing all the examples from this guide, download it here. Or if you have a specific use case that's giving you trouble, leave a comment below—I read every one and typically respond within 48 hours.

← Back to Home