Excel VBA Lesson 4: Using Excel VBA Operators
Continue learning classic Excel VBA with the same shared lesson template and cleaner visual style.
Operators are the building blocks of Excel VBA programming, allowing you to perform calculations, make comparisons, and control program flow. Mastering operators is essential for writing efficient VBA code.
4.1 Excel VBA Arithmetic Operators: Performing Mathematical Calculations.
Arithmetic operators perform mathematical calculations in your VBA code. These are fundamental for any data processing tasks in Excel.
| Operator | Name | Description | Example | Result |
|---|---|---|---|---|
| ^ | Exponentiation | Raises a number to the power of another | 2 ^ 3 |
8 |
| * | Multiplication | Multiplies two numbers | 5 * 4 |
20 |
| / | Division | Divides two numbers (returns decimal) | 10 / 3 |
3.333... |
| \ | Integer Division | Divides two numbers (returns integer) | 10 \ 3 |
3 |
| Mod | Modulus | Returns remainder after division | 10 Mod 3 |
1 |
| + | Addition | Adds two numbers or concatenates strings | 7 + 3 |
10 |
| - | Subtraction | Subtracts two numbers | 7 - 3 |
4 |
| & | Concatenation | Joins strings (preferred method) | "Hello " & "World" |
"Hello World" |
Operator Precedence in VBA
When multiple operators appear in an expression, VBA evaluates them in this order:
^(Exponentiation)-(Negation, as in -5)*and/(Multiplication and Division)\(Integer Division)Mod+and-(Addition and Subtraction)&(Concatenation)
Practical Example: Calculating Discounts
Sub CalculateDiscount()
Dim originalPrice As Double
Dim discountRate As Double
Dim finalPrice As Double
originalPrice = 100
discountRate = 0.15 ' 15% discount
' Calculate final price with discount
finalPrice = originalPrice - (originalPrice * discountRate)
MsgBox "The discounted price is: $" & finalPrice
End Sub
4.2 Excel VBA Comparison Operators
Comparison operators evaluate relationships between values and return True or False. These are essential for decision-making in your VBA code.
| Operator | Name | Example | Result |
|---|---|---|---|
| = | Equal to | 5 = 5 |
True |
| <> | Not equal to | 5 <> 3 |
True |
| < | Less than | 3 < 5 |
True |
| > | Greater than | 5 > 3 |
True |
| <= | Less than or equal to | 5 <= 5 |
True |
| >= | Greater than or equal to | 5 >= 5 |
True |
Practical Example: Grade Evaluation
Sub EvaluateGrade()
Dim score As Integer
score = 85
If score >= 90 Then
MsgBox "Grade: A"
ElseIf score >= 80 Then
MsgBox "Grade: B"
ElseIf score >= 70 Then
MsgBox "Grade: C"
ElseIf score >= 60 Then
MsgBox "Grade: D"
Else
MsgBox "Grade: F"
End If
End Sub
4.3 Excel VBA Logical Operators
Logical operators combine multiple conditions and return Boolean results (True or False). These are powerful tools for complex decision-making.
| Operator | Name | Description | Example | Result |
|---|---|---|---|---|
| And | Logical AND | True if both conditions are true | (5 > 3) And (2 < 4) |
True |
| Or | Logical OR | True if either condition is true | (5 > 3) Or (2 > 4) |
True |
| Not | Logical NOT | Reverses the logical result | Not (5 > 3) |
False |
| Xor | Exclusive OR | True if exactly one condition is true | (5 > 3) Xor (2 > 4) |
True |
Practical Example: Loan Approval System
Sub CheckLoanApproval()
Dim creditScore As Integer
Dim annualIncome As Currency
Dim hasCollateral As Boolean
creditScore = 720
annualIncome = 85000
hasCollateral = True
' Loan approval rules:
' - Credit score > 700 AND income > $80,000
' OR
' - Has collateral AND income > $50,000
If (creditScore > 700 And annualIncome > 80000) Or _
(hasCollateral And annualIncome > 50000) Then
MsgBox "Loan Approved!"
Else
MsgBox "Loan Denied"
End If
End Sub
Common Operator Mistakes to Avoid
Performance Tips for Using Operators
- Use Integer Division (\) when possible: It's faster than regular division if you don't need decimal places
- Minimize string concatenation: Each & operation creates a new string, which can be slow in loops
- Order conditions wisely: Place most likely-to-fail conditions first in And expressions, most likely-to-pass first in Or expressions
- Use parentheses liberally: They make your intentions clear and prevent precedence-related bugs
Summary: Key Takeaways
✅ In This Lesson, You Learned:
- Arithmetic Operators: Perform calculations (
+ - * / ^ Mod \ &) with specific precedence rules - Comparison Operators: Compare values (
= <> < > <= >=) returning Boolean results - Logical Operators: Combine conditions (
And Or Not Xor) for complex decision-making - Best Practices: Use
&for concatenation, parentheses for clarity, and understand precedence
📝 Practice Exercise:
Create a VBA macro that:
- Calculates the area of a rectangle (length × width)
- Determines if a number is even (using Mod operator)
- Checks if a year is a leap year (divisible by 4 but not 100, unless also divisible by 400)
Frequently Asked Questions
Q: What's the difference between / and \ operators?
A: / performs regular division (returns decimal), while \ performs integer division (truncates decimal).
Q: Why does "5" + "5" give 10 but "5" & "5" give "55"?
A: + tries to convert to numbers if possible, while & always concatenates as strings.
Q: How does VBA compare strings with comparison operators?
A: Alphabetically based on ASCII values (A < B < C...), case-insensitive by default unless Option Compare Text is specified.
🔗 Related Resources