VBA Operators
VBA operators are special tokens that instruct the compiler to “operate” on values or program identifiers. They are also referred to as program symbols or code elements. Also, the program identifiers they operate on (e.g., addition) must be capable of holding values.
You may have heard of the term operand. These are the values (i.e., literals) or identifiers (e.g., variables and constants) that operators act on. Based on their number of operands, operators are either unary or binary.
Unary VBA operators are operators that only act on a single operand at a time. Binary VBA operators are those that only act on two operands at a time.
VBA supports the following categories of operators:
- Assignment Operator;
- Member Access Operators;
- Concatenation Operators;
- Arithmetic Operators;
- Comparison Operators;
- Logical Operators.
This article takes an in-depth look at the VBA comparison operators.
VBA Operator Precedence
Often, an operation involves more than one operator, sometimes of different categories. So, it is worthwhile paying special attention to the order of precedence of the VBA operators. Otherwise, VBA’s default operator precedence applies.
The default precedence is as follows: arithmetic first, then concatenation, followed by comparison, then logical, and finally assignment operators.
Moreover, there is a pre-set precedence for operators within each category. How do you override this default order and remove any ambiguity? Easy, set the preferred precedence with open and close parentheses, ( ).
Comparison Operators
Comparison operators perform relational, object equality, and string match operations on a pair of operands. The table below summarizes the various comparison operators supported by VBA.
Operator | Description | Return Data Type | Order |
---|---|---|---|
= | Equality (binary) operator tests whether the values held by its two operands are equal/identical. | Boolean – True (i.e., ≠ 0) if the values held by the operands are equal, otherwise it returns False (i.e., = 0). | 1 |
< > | Inequality (binary) operator tests whether the values held by its two operands are NOT equal/identical. | Boolean – True (i.e., ≠ 0) if the values held by the operands are NOT equal, otherwise it returns False (i.e., = 0). | 1 |
> | Greater Than (binary) operator tests whether the value held by the operand to the left of the operator is greater than that held by the operand to its right. | Boolean – True (i.e., ≠ 0) if the value held by left-side operand is greater than the value held by the right-side operand, otherwise it returns False (i.e., = 0). | 1 |
> = | Greater Than or Equal To (binary) operator tests whether the value held by the operand to the left of the operator is greater than or equal to that held by the operand to its right. | Boolean – True (i.e., ≠ 0) if the value held by left-side operand is greater than or equal to the value held by the right-side operand, otherwise it returns False (i.e., = 0). | 1 |
< | Greater Than (binary) operator tests whether the value held by the operand to the left of the operator is less than that held by the operand to its right. | Boolean – True (i.e., ≠ 0) if the value held by left-side operand is less than the value held by the right-side operand, otherwise it returns False (i.e., = 0). | 1 |
< = | Greater Than or Equal To (binary) operator tests whether the value held by the operand to the left of the operator is less than or equal to that held by the operand to its right. | Boolean – True (i.e., ≠ 0) if the value held by left-side operand is less than or equal to the value held by the right-side operand, otherwise it returns False (i.e., = 0). | 1 |
Is | Object Reference Comparison (binary) operator tests whether two object variables reference (i.e., point to) the same object (i.e., memory address). | Boolean – True (i.e., ≠ 0) if the object variables refer to the same object, otherwise it returns False (i.e., = 0). | 1 |
Like | String Pattern Comparison (binary) operator tests whether two String operands match, i.e. have the same number of characters and in the same sequence. | Boolean – True (i.e., ≠ 0) if the left-side operand matches the right-side operand, otherwise False (i.e., = 0); Null, if either operand is Null. | 1 |
As shown in the table, comparison operators all have equal precedence. So, when several of them appear together in an expression, their evaluation proceeds in the order of appearance from left to right.
Also, enclosing a part of an expression in parentheses causes its evaluation ahead of other parts.
Comparison Operators: Relational (=, <>, >, >=, <, and <=)
The sample code below illustrates the =, <>, >, >=, <, and <= comparison operators’ usage.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
Sub ComparisonOperator_Example01() Dim lVar_Var1 As Variant, lVar_Var2 As Variant 'equality operator lVar_Var1 = "Snake": lVar_Var2 = "Snake" If lVar_Var1 = lVar_Var2 Then Debug.Print lVar_Var1 & " = "; lVar_Var2 'inequality operator lVar_Var1 = 23: lVar_Var2 = 36 If lVar_Var1 <> lVar_Var2 Then Debug.Print lVar_Var1 & " <> "; lVar_Var2 'greater than operator If lVar_Var2 > lVar_Var1 Then Debug.Print lVar_Var2 & " > "; lVar_Var1 'less than operator If lVar_Var1 < lVar_Var2 Then Debug.Print lVar_Var1 & " < "; lVar_Var2 'greater than or equal to operator If lVar_Var2 >= lVar_Var1 Then Debug.Print lVar_Var2 & " >= "; lVar_Var1 'less than or equal to operator If lVar_Var1 <= lVar_Var2 Then Debug.Print lVar_Var1 & " <= "; lVar_Var2 End Sub |
Comparison Operators: Object Reference (Is)
The sample code below demonstrates the Is (or Object Reference) comparison operator’s usage.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Sub ComparisonOperator_Example02() 'declare object variables to reserve memory space/address for them Dim lObj_Var1 As Object, lObj_Var2 As Object 'Set statement assigns object references Set lObj_Var1 = lObj_Var2 'Is operator tests whether any 2 objects refer to the same address If lObj_Var1 Is lObj_Var2 Then Debug.Print _ "lObj_Var1 & lObj_Var2 refer to the same memory address" 'both object variables can also be set to the same address by ' setting each to another object variable Dim lObj_Var3 As Object Set lObj_Var1 = lObj_Var3: Set lObj_Var1 = lObj_Var3 End Sub |
Comparison Operators: String Matching (Like)
String comparisons depend on the Option Compare statement placed atop the module (i.e., before the code for any procedures). The Like comparison operator is not exempt.
Option Compare Binary is the default setting and amounts to case-sensitive comparisons. On the other hand, Option Compare Text leads to case-insensitive comparisons.
Note that the Like operator can’t be used in a Select Case statement.
The sample code below shows the Like comparison operator’s usage.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
Sub ComparisonOperator_Like_Example01() 'demo: True, False, and Null match-returns Dim lVar_Result As Variant 'strings match lVar_Result = "Quick brown fox" Like "Quick brown fox" Debug.Print "When operands match, result = " Debug.Print lVar_Result 'strings do not match lVar_Result = "Quick brown fox" Like "Quick brown fo" Debug.Print "When operands do not match, result = " Debug.Print lVar_Result 'one string is Null lVar_Result = "Quick brown fox" Like Null Debug.Print "When either operand is Null, result = " Debug.Print lVar_Result End Sub |
Using Wildcards with the Like Comparison Operator
VBA supports built-in pattern matching using wildcard characters to turbocharge string comparisons. You can include wildcard characters, character lists, or character ranges (or a mix of these) in the Like operator’s operands to achieve the desired match.
The table below summarizes the valid VBA pattern matching wildcards.
Wild Card | What Wild Card Matches in a String |
---|---|
? | Any single character. |
# | Any single digit (0 – 9). |
[ charlist ] | Any single character in charlist. |
[ !charlist ] | Any single character not in charlist. |
* | Zero or more characters. |
The sample code below illustrates the power of combining wildcards and the Like comparison operator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
Sub ComparisonOperator_Like_Example02() 'demo: using wildcard characters with the Like operator Dim lVar_Result As Variant 'matching using any single character wildcard (?) lVar_Result = "Quick" Like "Qu?ck" Debug.Print "The ? in operand-2 matches it with operand-1," & _ " result = " & lVar_Result 'matching using zero or more characters wildcard (*) lVar_Result = "Quickly" Like "Quick*" Debug.Print "The * at operand-2's end matches it with operand-1," & _ " result = " & lVar_Result 'matching using any single digit (0-9) wildcard (#) lVar_Result = "2020, what a year" Like "2#2#, what a year" Debug.Print "The #s in operand-2 matches it with operand-1," & _ " result = "; lVar_Result 'matching using any single character in charlist wildcard ([]) lVar_Result = "Quick" Like "Qu[ijk]ck" Debug.Print "The 'i' in [ijk], in operand-2, matches it with" & _ " operand - 1, result = " & lVar_Result 'matching using any single character NOT in charlist wildcard ([!]) lVar_Result = "Quick" Like "Qu[!abc]ck" Debug.Print "As 'i' is NOT in [abc], in operand-2, both" & _ " operands match, result = " & lVar_Result End Sub |
Sometimes the wildcard characters, left bracket ‘[,‘ question mark ‘?,’ hash ‘#,’ asterisk ‘*,’ and right bracket ‘],’ themselves may need to be matched in a string.
While the left bracket ‘[,‘ question mark ‘?,’ hash ‘#,’ and asterisk ‘*’ can be matched by placing them inside brackets, “[ ],” the right bracket, ‘],’ cannot be used inside a group (i.e. [charlist]) to match itself.
Instead, as shown in the sample code below, match the right bracket, ‘],’ like any regular individual character, by placing it outside a group.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
Sub ComparisonOperator_Like_Example03() 'demo: matching the wildcard characters themselves Dim lVar_Result As Variant 'matching a question mark lVar_Result = "Pardon?" Like "Pardon[?]" Debug.Print "The [?] in operand-2 matches the '?' in operand-1," & _ " result = " & lVar_Result 'matching an asterisk lVar_Result = "F*X" Like "F[*]X" Debug.Print "The [*] in operand-2 matches the '*' in operand-1," & _ " result = " & lVar_Result 'matching a hash lVar_Result = "Astronomical #s" Like "Astronomical [#]s" Debug.Print "The [#] in operand-2 matches the '#' in operand-1," & _ " result = " & lVar_Result 'matching a left-bracket and right-bracket lVar_Result = "Thrice[3X]" Like "Thrice[[]3X]" Debug.Print "The [[] and ']' in operand-2 match the " & _ "'[' and ']' in operand-1, result = " & lVar_Result End Sub |
You’ll often need to match a character inside or outside a character-range to a character in a string. Think of digits (0-9), uppercase letters (A-Z), and lowercase letters (a-z) character-ranges.
In such cases, use the [charlist], or [!charlist], to capture the range. Also, separate the range’s upper and lower bounds with a hyphen, (-).
Moreover, multiple ranges can be written in a single charlist. Delimiters (e.g., space, comma) are invalid between each range.
The sample code below illustrates the foregoing string matching capability.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
Sub ComparisonOperator_Like_Example04() 'demo: matching characters in a range using hyphen & wildcards Dim lVar_Result As Variant 'matching a character within a range defined by '-' and "[charlist]" lVar_Result = "Open Sesame" Like "Open [A-Z]esame" Debug.Print "The [A-Z] in operand-2 matches the 'S' in operand-1," & _ " result = " & lVar_Result 'matching a character NOT in a range defined by '-' and "[charlist]" lVar_Result = "Open Sesame" Like "Open [!a-z]esame" Debug.Print "The [!a-z] in operand-2 matches the 'S' in operand-1," & _ " result = " & lVar_Result 'matching characters with multiple ranges" lVar_Result = "Year 70 AD" Like "Year [!A-Z][!a-z] AD" Debug.Print "The [!A-Z] & [!a-z] in operand-2 matches '7' & '0'" & _ " in operand-1, result = " & lVar_Result 'the impact of the Option Compare statement lVar_Result = "Open Sesame" Like "Open [a-z]esame" Debug.Print "The [a-z] in operand-2 cannot match the 'S' in " & _ "operand-1 as comparison" & vbCrLf & " is case-sensitive " & _ "(i.e., Option Compare Binary), result = " & lVar_Result 'outside "[]", hyphen '-' & bang '!' are treated like regular chars. lVar_Result = "-Hyphen!" Like "-Hyphen!" Debug.Print "The '-' & '!' in operand-2 match the '-' & '!'" & _ " in operand-1, result = " & lVar_Result 'matching a character within a range defined by '-' and "[charlist]" lVar_Result = "Open Sesame" Like "Open [A-Z]esame" Debug.Print "The [A-Z] in operand-2 matches the 'S' in operand-1," & _ " result = " & lVar_Result End Sub |
Note that character ranges must be specified in ascending sort order (i.e., smallest to largest). So, [0-9] is a valid pattern, but [9-0] is not. Lastly, the compiler treats an empty character list, i.e. [], as a zero-length string (“”).