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 assignment operator.
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, ( ).
Assignment Operator
VBA supports a single assignment operator, =. It stores the value of the operand on its right in the operand on its left. Afterward, both operands hold the same value.
Moreover, the operand on the right can comprise several expressions. Note that expressions are combinations of operands and operators. Meanwhile, the identifier on the left must be a value-holding program identifier.
In any case, both operands must be of the same data type. Otherwise, they can’t hold the same values.
So, the assignment operator writes the value of the right-side expression to the memory address of the left-side program identifier.
The sample code below illustrates the assignment operator’s usage.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Option Explicit Sub AssignmentOperator_Example01() Dim x As Integer, y As Integer, z As Integer 'left-side value gets written into right-side identifier" x = 1: y = 3: z = 5 Debug.Print "x = "; x & ", y = "; y & ", z = "; z 'assignments cannot be chained z = y = x = 10 Debug.Print "x = "; x & ", y = "; y & ", z = "; z End Sub |
The sample code also shows that, unlike in languages such as C, assignments cannot be chained in VBA. The results in the Immediate window (see the image below) demonstrate this.
Besides the assignment operator, there are several expression statements that also perform assignments. These include the Let, Set, Get, Put, Input #, Line Input #, Print #, and Write # statements.