Not Equal in Excel VBA: Using the <> Operator
In this article
The "not equal to" operator in Excel VBA is <>. This operator is used in conditional statements to determine if two values, variables, or expressions are different from one another, returning True if they are not identical and False if they are.
How the Not Equal Operator Works
In VBA (Visual Basic for Applications), the <> symbol is a combination of the "less than" and "greater than" signs. Logically, if a value is neither less than nor greater than another value, it must be equal to it; therefore, if it is either less than OR greater than, it cannot be equal. This is the standard way to express inequality in the language.
When the VBA compiler encounters <>, it compares the data types and values of the operands on both sides. If the values differ in any way—including case sensitivity for strings or precision for floating-point numbers—the expression evaluates to True. This is most commonly utilized within If...Then statements, Do While loops, and Select Case blocks to control the flow of a macro based on specific criteria.
Using Not Equal in Conditional Logic
The most frequent application of the <> operator is within an If statement. This allows a programmer to execute a specific block of code only when a certain condition is not met. For example, if you are scanning a column of data and want to perform an action on every cell except those that contain the word "Complete", you would use the not equal operator.
Consider a scenario where you are validating user input in a cell. You might want to ensure that a cell is not empty before proceeding with a calculation. In VBA, an empty cell can be represented by an empty string (""). A typical logic structure would look like this:
If Range("A1").Value <> "" Then: This checks if the value in cell A1 is not equal to an empty string.If myVariable <> 0 Then: This ensures a numeric variable is not zero to avoid "Division by Zero" errors during mathematical operations.If ActiveSheet.Name <> "Summary" Then: This allows a macro to run on all worksheets except the one named "Summary".
Comparing Different Data Types
The behavior of the <> operator changes slightly depending on the data type being compared. Understanding these nuances is critical to avoiding bugs in your Excel macros.
String Comparisons
By default, VBA string comparisons are case-sensitive. This means that "Apple" <> "apple" will evaluate to True because the uppercase 'A' and lowercase 'a' have different character codes. If you want to perform a "case-insensitive" not-equal comparison, you have two primary options:
- Using UCase or LCase: Convert both sides to the same case. For example:
If UCase(cellValue) <> UCase("Completed") Then. - Option Compare Text: Placing
Option Compare Textat the very top of your module tells VBA to ignore case for all string comparisons in that module.
Numeric Comparisons
When comparing integers or longs, <> is straightforward. However, when dealing with Double or Single (floating-point numbers), precision issues can occur. Because of how computers store decimals in binary, a calculation that should result in 1.0 might actually result in 0.99999999999999. In such cases, myValue <> 1.0 might return True even when the value appears to be 1.0 in the Excel grid. To handle this, it is often better to check if the absolute difference between two numbers is greater than a very small threshold (epsilon).
Object Comparisons
When comparing objects (like a Worksheet or a Range), you cannot use the standard <> operator directly on the object variables. Instead, you must use the Is keyword combined with the Not operator. For example, to check if a worksheet object is not equal to another, you would write If Not ws1 Is ws2 Then. Using <> on objects will typically result in a "Type Mismatch" error because VBA tries to compare the default properties of the objects rather than the objects themselves.
Common Problems and Pitfalls
Even experienced developers encounter issues when using the not equal operator. Most of these stem from a misunderstanding of how VBA handles Null, Empty, and Nothing.
- The Null Trap: In database contexts (like using ADODB), a
Nullvalue represents missing data. Any comparison using<>against aNullvalue will result inNull, notTrueorFalse. To check if a value is not null, you must use theIsNull()function:If Not IsNull(myValue) Then. - Empty vs. Zero: A variable that has not been initialized is
Empty. WhileEmpty <> 0might evaluate toFalsein some contexts because VBA coerces the empty value to a zero for numeric comparisons, it is safer to useIsEmpty()to check for initialization. - Trailing Spaces: A common reason why
<>returnsTruewhen you expectFalseis the presence of invisible trailing or leading spaces in a cell."Active " <> "Active"isTrue. Using theTrim()function—e.g.,If Trim(cellValue) <> "Active" Then—is the best way to prevent this.
Alternatives to the Not Equal Operator
While <> is the direct way to express inequality, there are other logical structures that can achieve the same result, sometimes with better readability or functionality.
The Not Operator
You can wrap an equality check in a Not operator. For example, If Not (x = y) Then is logically identical to If x <> y Then. This is particularly useful when you are dealing with Boolean functions. If you have a function called IsValid() that returns True or False, you would use If Not IsValid() Then to execute code when the condition is not met.
Select Case Statements
When you have multiple "not equal" conditions, a long string of ElseIf statements can become messy. A Select Case block can be cleaner. While Select Case is usually used for equality, you can use Case Else to handle everything that didn't match the previous criteria, effectively acting as a "not equal to any of the above" catch-all.
Frequently Asked Questions
Why does VBA say "Type Mismatch" when I use <>?
This usually happens when you try to compare two incompatible data types, such as comparing a String variable to a Range object, or trying to use <> to compare two object variables. Ensure both sides of the operator are of the same type, or use the CStr(), CInt(), or CDbl() functions to convert them to a matching type before comparing.
Is there a difference between <> and != in VBA?
Yes. In many modern languages like C#, Java, or Python, != is used for not equal. However, VBA does not recognize !=. If you use != in a VBA module, the editor will throw a syntax error. You must use <>.
How do I check if a cell is not equal to a blank cell?
The most reliable way is to check if the cell value is not equal to an empty string: If Range("A1").Value <> "" Then. Alternatively, you can use If Not IsEmpty(Range("A1")) Then, though IsEmpty specifically checks if the cell has never been initialized, whereas <> "" checks if the cell currently contains no text.
Can I use the not equal operator with dates?
Yes, you can use <> with Date variables. For example, If myDate <> Date Then will return True if myDate is any day other than today. Just ensure that both variables are explicitly declared as Date types to avoid errors related to regional date formatting strings.
Does <> work with arrays?
No, you cannot compare two entire arrays using Array1 <> Array2. VBA does not support direct array-to-array comparison. To determine if two arrays are not equal, you must write a loop that iterates through each element of the arrays and compares them individually. If any single pair of elements is not equal, then the arrays as a whole are not equal.