VBA Operators
Operators perform actions on values and return a result. Operations work much like functions as they take input values, do an operation, and return an output value. There are arithmetic operators, string concatenation operators, comparison operators, logical operators, and bitwise operators. Expressions are created by joining values or expressions using operators.
Operator Precedence
Operator Precedence is the order in which operators are evaluated in an expression.
Precedence Order
-
-
Parentheses
- Parentheses: ()
-
Arithmetic Operators
- Exponentiation: ^
- Unary Identity and Negation: +, -
- Multiplication and Floating-Point Division: *, /
- Integer Division: \
- Remainder Division: Mod
- Addition and Subtraction: +, -
-
Concatenation Operators
- String Concatenation: &, +
-
Comparison Operators
- All Comparison Operators: =, <>, <, <=, >, >=, Like, Is, TypeOf...Is
-
Logical and Bitwise Operators
- Not
- And
- Or
- Xor
- Eqv
- Imp
-
Parentheses
Associativity
Operators of equal precedence will be interpreted from left to right.
Public Sub Example()
Debug.Print 10 / 5 * 2 'Prints: 4
Debug.Print (10 / 5) * 2 'Prints: 4
End Sub
Parentheses
Expressions inside parentheses are evaluated first. Parentheses are used to override precedence order.
Public Sub Example()
Dim Result As Long
Result = 1 + 2 * 3
Debug.Print Result 'Prints: 7
Result = (1 + 2) * 3
Debug.Print Result 'Prints: 9
End Sub
Arithmetic Operators
Arithmetic Operators are used to perform mathematical operations on numbers.
Operator | Operation | Example |
---|---|---|
^ | Exponentiation | 2 ^ 2 |
+,- | Unary Identity and Negation | -2 |
* | Multiplication | 2 * 5 |
/ | Floating-Point Division | 10 / 2 |
\ | Integer Division | 5 \ 2 |
Mod | Remainder Division | 4 Mod 2 |
+ | Addition | 2 + 2 |
- | Subtraction | 4 - 2 |
Concatenation Operators
Concatenation Operators are used to join strings together. The & and + string concatenation operators both join strings together however the & operator will convert any non-string argument to a string whereas the + operator will not. If the + operator is used to combine a string with a non-string an error will occur. The CStr function can be used to explicitly convert non-string values to strings.
Operator | Operation |
---|---|
& | Implicit String Conversion |
+ | No Implicit String Conversion |
Public Sub Example()
Debug.Print "Hello, " & "World!"
Debug.Print "Hello, " & 100
Debug.Print "Hello, " + "World!"
Debug.Print "Hello, " + 100 'Causes an Error. No implicit string conversion.
Debug.Print "Hello, " + CStr(100)
End Sub
Comparison Operators
Comparison Operators are used to compare values and return True or False.
Operator | Operation |
---|---|
> | Greater Than |
< | Less Than |
>= | Greater Than or Equal To |
<= | Less Than or Equal To |
= | Equal To |
<> | Not Equal To |
Like | Compare text using Wildcards |
Is | Check if Object variables refer to the same Object |
TypeOf...Is | Check the type of an Object variable |
Public Sub Example()
Debug.Print 100 > 50
Debug.Print 50 < 100
Debug.Print 25 >= 25
Debug.Print 25 <= 25
Debug.Print 50 = 50
Debug.Print 2 <> 3
End Sub
Strings
When comparing strings using comparison operators, the comparison method used is determined by the Option Compare statement. If no Option Compare statement is used, strings are compared using their underlying Binary representations by default (Same as using Option Compare Binary). The StrComp function provides finer control over string comparison by allowing the compare method to be specified.
Option Explicit
Option Compare Binary
Public Sub Example()
Debug.Print "A" <> "a"
End Sub
Option Explicit
Option Compare Text
Public Sub Example()
Debug.Print "A" = "a"
End Sub
Option Explicit
Public Sub Example()
Debug.Print StrComp("A", "a", vbTextCompare) = 0
End Sub
The Like operator can be used to compare strings using Wildcard characters to match text patterns.
Public Sub Example()
Debug.Print "Hello, World!" Like "Hello*"
End Sub
Objects
The Is keyword can be used to check if two object variables refer to the same object in memory. When objects are compared using Is, the data stored in the object's fields are not compared. A function would need to be created that compares each member of an object, given the object's type.
Public Sub Example()
Dim C1 As Collection
Dim C2 As Collection
Set C1 = New Collection
Set C2 = New Collection
Debug.Print C1 Is C2 'Prints: False
Set C2 = C1
Debug.Print C1 Is C2 'Prints: True
End Sub
TypeOf...Is can be used to check an object's type. This should be used when an object is declared using the generic Object type and a certain action requires the object to be of a certain type.
Public Sub Example()
Dim Obj As Object
Set Obj = New Collection
If TypeOf Obj Is Collection Then
Debug.Print Obj.Count
Else
Debug.Print "Obj is not Collection object"
End If
End Sub
Logical Operators
Logical Operators are used to perform logical operations. Logical operations result in True or False. Logical operators can be used to join together conditional statements into more complex logical expressions. In VBA, there are no short-circuit logical operators. This means that all conditions will be evaluated in a logical expression without regard to the outcome of a previous condition. For example, when using a logical And, both conditions need to be True for the expression to return True. Thus, if the first condition is False, the expression could skip evaluating the next condition and immediately return False. In VBA however, evaluation will continue even if the result could already be determined.
Note: There are no short-circuit logical operators in VBA.
Operator | Operation |
---|---|
And | Logical And |
Or | Logical Or |
Xor | Logical Exclusive Or |
Not | Logical Not |
Eqv | Logically Equivelent |
Imp | Logical Implication |
Option Explicit
Public Sub TestAnd()
Debug.Print True And True 'True
Debug.Print True And False 'False
Debug.Print False And True 'False
Debug.Print False And False 'False
Debug.Print True And Null 'Null
Debug.Print Null And True 'Null
Debug.Print False And Null 'False
Debug.Print Null And False 'False
Debug.Print Null And Null 'Null
End Sub
Public Sub TestOr()
Debug.Print True Or True 'True
Debug.Print True Or False 'True
Debug.Print False Or True 'True
Debug.Print False Or False 'False
Debug.Print True Or Null 'True
Debug.Print Null Or True 'True
Debug.Print False Or Null 'Null
Debug.Print Null Or False 'Null
Debug.Print Null Or Null 'Null
End Sub
Public Sub TestXor()
Debug.Print True Xor True 'False
Debug.Print True Xor False 'True
Debug.Print False Xor True 'True
Debug.Print False Xor False 'False
Debug.Print True Xor Null 'Null
Debug.Print Null Xor True 'Null
Debug.Print False Xor Null 'Null
Debug.Print Null Xor False 'Null
Debug.Print Null Xor Null 'Null
End Sub
Public Sub TestNot()
Debug.Print Not True 'False
Debug.Print Not False 'True
Debug.Print Not Null 'Null
End Sub
Public Sub TestEqv()
Debug.Print True Eqv True 'True
Debug.Print True Eqv False 'False
Debug.Print False Eqv True 'False
Debug.Print False Eqv False 'True
Debug.Print True Eqv Null 'Null
Debug.Print Null Eqv True 'Null
Debug.Print False Eqv Null 'Null
Debug.Print Null Eqv False 'Null
Debug.Print Null Eqv Null 'Null
End Sub
Public Sub TestImp()
Debug.Print True Imp True 'True
Debug.Print True Imp False 'False
Debug.Print False Imp True 'True
Debug.Print False Imp False 'True
Debug.Print True Imp Null 'Null
Debug.Print Null Imp True 'True
Debug.Print False Imp Null 'True
Debug.Print Null Imp False 'Null
Debug.Print Null Imp Null 'Null
End Sub
And
True if both conditions are true
Condition 1 | Condition 2 | Result |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
True | Null | Null |
Null | True | Null |
False | Null | False |
Null | False | False |
Null | Null | Null |
Or
True if at least one condition is true
Condition 1 | Condition 2 | Result |
---|---|---|
True | True | True |
True | False | True |
False | True | True |
False | False | False |
True | Null | True |
Null | True | True |
False | Null | Null |
Null | False | Null |
Null | Null | Null |
Xor
True if one and only one condition is true
Condition 1 | Condition 2 | Result |
---|---|---|
True | True | False |
True | False | True |
False | True | True |
False | False | False |
True | Null | Null |
Null | True | Null |
False | Null | Null |
Null | False | Null |
Null | Null | Null |
Not
True if False, False if True
Condition 1 | Result |
---|---|
True | False |
False | True |
Null | Null |
Eqv
True if conditions are logically equivelent, otherwise False
Condition 1 | Condition 2 | Result |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | True |
True | Null | Null |
Null | True | Null |
False | Null | Null |
Null | False | Null |
Null | Null | Null |
Imp
If Condition1 is True, Condition2 must be True. If Condition1 is False, Condition2 can be True or False.
If I am a fish, I breathe water. If I am not a fish, I may breathe water or not.
Condition 1 | Condition 2 | Result |
---|---|---|
True | True | True |
True | False | False |
False | True | True |
False | False | True |
True | Null | Null |
Null | True | True |
False | Null | True |
Null | False | Null |
Null | Null | Null |
Bitwise Operators
Bitwise Operators are used to logically compare the bits of binary representations of numbers and return a number representing the result of the bitwise comparison. The number of bits differs depending on the integral data type being compared and every bit is considered when doing bitwise comparisons. For example, when comparing an 8-bit integer to an 16-bit integer, the 8-bit integer will be treated like a 16-bit integer with the first 8 bits set to 0's so that all 16 bits can be compared.
And
Bitwise And reads integers as Binary and compares each bit using And logic.
Public Sub Example()
Dim Num1 As Byte
Dim Num2 As Byte
Dim Result As Byte
Num1 = 6 '00000110 in binary
Num2 = 12 '00001100 in binary
Result = Num1 And Num2
Debug.Print Result 'Prints 4 -> 00000100 in binary
End Sub
Or
Bitwise Or reads integers as Binary and compares each bit using Or logic.
Public Sub Example()
Dim Num1 As Byte
Dim Num2 As Byte
Dim Result As Byte
Num1 = 6 '00000110 in binary
Num2 = 12 '00001100 in binary
Result = Num1 Or Num2
Debug.Print Result 'Prints 14 -> 00001110 in binary
End Sub
Xor
Bitwise Xor reads integers as Binary and compares each bit using Xor logic.
Public Sub Example()
Dim Num1 As Byte
Dim Num2 As Byte
Dim Result As Byte
Num1 = 6 '00000110 in binary
Num2 = 12 '00001100 in binary
Result = Num1 Xor Num2
Debug.Print Result 'Prints 10 -> 00001010 in binary
End Sub
Not
Bitwise Not reads an integer as Binary and reverses each bit.
Public Sub Example()
Dim Num As Byte
Dim Result As Byte
Num = 3 '00000011 in binary
Result = Not Num
Debug.Print Result 'Prints 252 -> 11111100 in binary
End Sub
Eqv
Bitwise Eqv reads an integer as Binary and compares each bit using Eqv logic.
Public Sub Example()
Dim Num1 As Byte
Dim Num2 As Byte
Dim Result As Byte
Num1 = 6 '00000110 in binary
Num2 = 12 '00001100 in binary
Result = Num1 Eqv Num2
Debug.Print Result 'Prints 245 -> 11110101
End Sub
Imp
Bitwise Imp reads an integer as Binary and compares each bit using Imp logic.
Public Sub Example()
Dim Num1 As Byte
Dim Num2 As Byte
Dim Result As Byte
Num1 = 6 '00000110 in binary
Num2 = 12 '00001100 in binary
Result = Num1 Imp Num2
Debug.Print Result 'Prints 253 -> 11111101 in binary
End Sub
Assigment Operator
The assignment operator is used to assign values to variables. The left side of the assignment operator must be a variable and the right side of the assignment operator must be an expression that evaluates to a value that can be assigned to a variable.
Public Sub Example()
'Assign variable
Dim i As Long
i = 100
Let i = 100
'Assign Object variable
Dim Coll As Collection
Set Coll = New Collection
'Assign Constant
Const MESSAGE As String = "Hello, World!"
'Assign Property
Range("A1").Value = #01/01/2022#
End Sub
AddressOf Operator
The AddressOf operator is used to pass the address of a procedure to an API function which requires a function pointer as a parameter.
// C++ 64-bit ExampleDLL.dll
#define DLLExport __declspec(dllexport)
extern "C" {
DLLExport void __stdcall callSub(void (*funcPtr)()) {
funcPtr();
}
}
Option Explicit
Public Declare PtrSafe Sub callSub Lib "ExampleDLL.dll" (ByVal funcPtr As LongPtr)
Public Sub Example()
Call callSub(AddressOf SayHello)
End Sub
Public Sub SayHello()
Debug.Print "Hello, World!"
End Sub
Other
There a few operator-like symbols in VBA which perform specific functions.
Operator | Operation | Description |
---|---|---|
_ | Line Continuation | Continues a line of code on the next physical line. There is a limit of 25 consecutive physical joined lines using the continuation character (24 continuation characters). |
: | Statement Separator | Used to have more than 1 line of code on 1 physical line. Can also be used in the immediate window where only one physical line of code is permitted. |
? | Immediate Window Query | Used in immediate window to return a value from an expression. |
:= | Walrus Operator | Used to pass arguments to a procedure by name. |
Public Sub Example()
Dim Message As String
Message = "Hello, World!" & _
vbNewLine & _
"How are you?"
Debug.Print Message
End Sub
Public Sub Example()
Dim i As Long: For i = 1 To 10: Debug.Print i: Next i
End Sub
'In the immediate window:
?Range("A1").Value
?2 + 2
?UCase("hello, world!")
Public Sub Example()
PrintMessage Message:="Hello, World!"
End Sub
Public Sub PrintMessage(Message)
Debug.Print Message
End Sub