VBA course · Lesson 11 of 33
Operators and expressions in VBA
Arithmetic, joining text, comparisons, Like patterns, Is for objects, And/Or/Not, operator precedence and the overflow traps that catch VBA beginners.
An expression is any piece of code that VBA can work out to a single value: 2 + 3, price * qty, name & " Smith", sales > target. Operators are the symbols and keywords that combine values inside an expression. You have already used several of them in Variables and data types: Dim, Option Explicit and scope and Making decisions: If, ElseIf and Select Case. This lesson collects them all in one place, explains how VBA decides the order in which to evaluate them, and points out the surprises that differ from Excel formulas or from other programming languages.
Arithmetic operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
| + | Addition | 7 + 2 | 9 |
| - | Subtraction | 7 - 2 | 5 |
| * | Multiplication | 7 * 2 | 14 |
| / | Division (always a decimal result) | 7 / 2 | 3.5 |
| \ | Integer division (drops the remainder) | 7 \ 2 | 3 |
| Mod | Remainder after integer division | 7 Mod 2 | 1 |
| ^ | Power | 7 ^ 2 | 49 |
Most of these match Excel formulas. Two are new: the backslash \ for integer division and Mod for the remainder. Together they solve many everyday problems: how many full boxes, and how many items left over.
Option Explicit
Sub PackOrder()
Dim items As Long
Dim fullBoxes As Long
Dim leftOver As Long
items = 150
fullBoxes = items \ 12 ' 12 full boxes
leftOver = items Mod 12 ' 6 items in a part box
MsgBox items & " items = " & fullBoxes & " full boxes and " & leftOver & " loose items."
End SubMod is also the classic way to test whether a number is even (n Mod 2 = 0) or to do something every nth row (If r Mod 5 = 0 Then).
\ and Mod first round their operands to whole numbers using banker's rounding (0.5 goes to the nearest even number), so 7.5 \ 2 is 4, not 3. Work with whole numbers when you use them. The worksheet function MOD behaves differently with decimals and negative numbers, so do not assume the two always agree.The power operator also works for roots: 16 ^ 0.5 is 4 (the square root), and 27 ^ (1 / 3) is 3. Compound growth is a common use: a price of 100 growing 3% a year for 5 years is 100 * (1 + 0.03) ^ 5, about 115.93.
Joining text: & versus +
The & operator concatenates (joins) values into one string. It converts numbers and dates to text automatically:
Option Explicit
Sub InvoiceMessage()
Dim customer As String
Dim total As Currency
customer = "Harbor Foods"
total = 1249.5
MsgBox "Invoice for " & customer & ": " & Format(total, "#,##0.00") & " EUR"
End SubThe + sign can also join strings, but it is a trap. If both sides are text, it joins them. If one side is a number, it tries to add, and if the text is not numeric you get a "Type mismatch" error. Worse, with cell values (which are Variants) the result depends on what happens to be in the cells: Range("A1").Value + Range("B1").Value gives 15 for 10 and 5, but "105" if both cells contain the text "10" and "5". Always use & to join text and + only for numbers. Remember to put spaces around &; "a"&"b" may be misread by the editor.
Comparison operators
Comparisons produce True or False:
| Operator | Meaning |
|---|---|
| = | Equal to |
| <> | Not equal to |
| < | Less than |
| > | Greater than |
| <= | Less than or equal to |
| >= | Greater than or equal to |
In VBA the = sign does double duty: in total = 5 at the start of a statement it assigns a value, while inside an If or on the right side of an assignment it compares. So isBig = amount > 1000 stores True or False in the Boolean variable isBig.
Text comparisons are case-sensitive by default and compare letter by letter, so "apple" < "banana" is True, "Zebra" < "apple" is also True (capital letters come before lower-case ones in the character table), and "10" < "9" is True because the character "1" comes before "9". When you compare numbers stored as text, convert them first with CDbl or CLng. To ignore case, wrap both sides in UCase or LCase, or put Option Compare Text at the top of the module.
Pattern matching with Like
Like compares a string with a pattern and returns True or False. It is a lightweight alternative to regular expressions and is perfect for checking codes and formats.
| Pattern character | Matches |
|---|---|
| ? | Any single character |
| * | Zero or more characters |
| # | Any single digit 0–9 |
| [ABC] | Any one of the listed characters |
| [A-F] | Any character in the range |
| [!0-9] | Any character NOT in the list |
Option Explicit
Sub CheckProductCodes()
Dim r As Long
Dim code As String
For r = 2 To 8
code = Cells(r, "A").Value
If code Like "[A-Z][A-Z]-####" Then
Cells(r, "B").Value = "OK"
Else
Cells(r, "B").Value = "Bad format"
End If
Next r
End Sub| A | B | |
|---|---|---|
| 1 | Code | Check |
| 2 | KB-1001 | OK |
| 3 | MS-2040 | OK |
| 4 | kb-1001 | Bad format |
| 5 | MON-300 | Bad format |
| 6 | HD-77A1 | Bad format |
After running CheckProductCodes: codes must be two capital letters, a dash and four digits
Other handy patterns: email Like "*@*.*" for a rough e-mail check, name Like "Mc*" for names that start with Mc, and fileName Like "*.xlsx" for Excel files. Like is case-sensitive unless Option Compare Text is on.
Is: comparing objects
= compares values. To ask whether two object variables point at the same object, or whether an object variable is empty, you need Is:
Option Explicit
Sub FindCustomer()
Dim hit As Range
Set hit = Range("A:A").Find(What:="Harbor Foods", LookAt:=xlWhole)
If hit Is Nothing Then
MsgBox "Customer not found."
Else
MsgBox "Customer found in row " & hit.Row
End If
End SubFind returns Nothing when there is no match, and If hit = Nothing would not even compile. The pattern If obj Is Nothing Then appears constantly in VBA; you will use it again in Find, filter and sort data with VBA and Collections and dictionaries in VBA. To test the opposite, write If Not obj Is Nothing Then.
Logical operators: And, Or, Not, Xor
| Operator | True when |
|---|---|
| And | Both sides are True |
| Or | At least one side is True |
| Not | The value is False (it flips it) |
| Xor | Exactly one side is True |
No short-circuit evaluation
Many languages stop evaluating And as soon as the left side is False. VBA does not: it always evaluates both sides. That makes some innocent-looking lines crash:
Option Explicit
Sub AveragePrice()
Dim totalValue As Double
Dim qty As Long
totalValue = Range("B2").Value
qty = Range("C2").Value
' If qty <> 0 And totalValue / qty > 50 Then <-- crashes when qty = 0
If qty <> 0 Then
If totalValue / qty > 50 Then
Range("D2").Value = "Premium"
Else
Range("D2").Value = "Standard"
End If
Else
Range("D2").Value = "No quantity"
End If
End SubThe same applies to If Not hit Is Nothing And hit.Value > 0: when hit is Nothing, the right side still runs and raises an error. Nest the tests instead.
Operator precedence
When an expression contains several operators, VBA evaluates them in a fixed order:
- Brackets
( ) - Power
^ - Negation (a leading minus)
*and/- Integer division
\ Mod+and-- String concatenation
& - Comparisons
= <> < > <= >= Like Is Not, thenAnd, thenOr, thenXor
So 10 + 2 * 3 is 16, not 36, and "Total: " & 5 + 3 gives "Total: 8" because addition happens before joining. One difference from Excel: in VBA -2 ^ 2 is -4 (power first, then the minus), while the Excel formula =-2^2 gives 4. When in doubt, add brackets. They cost nothing and make your intention obvious to the next reader.
Overflow: when a number is too big for its type
Each numeric type has a limit (Variables and data types: Dim, Option Explicit and scope lists them). If a calculation's result exceeds the limit, VBA stops with Run-time error 6: Overflow. The nasty part is that VBA chooses the type of an intermediate result from its operands, not from the variable you store it in:
Option Explicit
Sub OverflowDemo()
Dim seconds As Long
' seconds = 24 * 60 * 60 * 2 <-- Overflow, although 172,800 easily fits in a Long
' Why? The literals 24, 60, 60 are Integers, so 24 * 60 * 60 = 86,400 overflows an Integer
seconds = 24& * 60 * 60 * 2 ' the & suffix makes 24 a Long, so the whole sum is Long
Debug.Print seconds ' 172800
seconds = CLng(300) * 200 ' CLng does the same job
Debug.Print seconds ' 60000
End SubSmall whole-number literals are treated as Integer (maximum 32,767). Multiplying two of them, or two Integer variables, overflows even if the target is a Long. Fixes: declare your variables As Long (good habit anyway), add the & type suffix to a literal, or convert one operand with CLng. Division by zero is a separate error (number 11), while 0 / 0 gives error 6 as well.
Common mistakes
- Joining text with
+and getting "Type mismatch" or "105" instead of 15. - Comparing objects with
=instead ofIs. - Expecting
Andto skip the right side when the left is False. - Forgetting that
"10" < "9"is True for text. - Writing
x = 1 Or 2when you meanx = 1 Or x = 2. - Integer overflow in intermediate results of
Integerarithmetic.
Check yourself
1. What is the result of 17 Mod 5?
17 divided by 5 is 3 with a remainder of 2; Mod returns the remainder.
2. Which operator should you use to join text in VBA?
& always produces text; + may try to add the values and cause a type mismatch.
3. Which test correctly checks that a Find found nothing?
Object variables are compared with Is; Nothing means "no object".
4. Does "AB-1234" Like "[A-Z][A-Z]-####" return True?
Two capital letters, a dash and four digits match the pattern.
5. Why does Dim n As Long: n = 200 * 200 raise an Overflow error?
Write 200& * 200 or CLng(200) * 200 so the calculation is done as a Long.