Excel VBA Classic Excel VBA 2010 Excel VBA 365 Excel VBA Examples About Us

Excel VBA Lesson 4: Using Excel VBA Operators


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.

Pro Tip: Operators in VBA follow a specific order of precedence that determines how expressions are evaluated. Understanding this hierarchy will help you write more predictable 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.


Table 4.1: Excel VBA Arithmetic Operators with Practical Examples
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"

Important Note: The & operator is preferred for string concatenation over + because it avoids type mismatch errors. For example, 1 & "2" works (result: "12") while 1 + "2" may cause errors.

Operator Precedence in VBA

When multiple operators appear in an expression, VBA evaluates them in this order:

  1. ^ (Exponentiation)
  2. - (Negation, as in -5)
  3. * and / (Multiplication and Division)
  4. \ (Integer Division)
  5. Mod
  6. + and - (Addition and Subtraction)
  7. & (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.

Table 4.2: Excel VBA Comparison Operators
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

String Comparison: VBA compares strings alphabetically (A < B < C ... < Z). Case sensitivity depends on the Option Compare setting at the top of your module. By default, string comparisons are case-insensitive.

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.

Table 4.3: Excel VBA Logical Operators
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

Short-Circuit Evaluation: VBA evaluates logical expressions from left to right and stops as soon as the outcome is determined. This can improve performance in complex expressions.

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

  1. Using = instead of ==: VBA uses single = for both assignment and comparison (unlike some languages)
  2. Confusing And with AndAlso: VBA doesn't have AndAlso/OrElse like VB.NET - it always evaluates all conditions
  3. Operator precedence errors: Forgetting that multiplication happens before addition (use parentheses to clarify)
  4. String vs numeric comparison: Comparing numbers stored as strings can give unexpected results ("10" < "2")

Performance Tips for Using Operators

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:

  1. Calculates the area of a rectangle (length × width)
  2. Determines if a number is even (using Mod operator)
  3. 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



Copyright ® 2008 Dr.Liew Voon Kiong . All rights reserved   [Privacy Policy]

Contact: Facebook Page