Mastering the building blocks of VBA expressions
Operators are fundamental elements in VBA programming used to perform computations, make comparisons, and combine expressions. Understanding operators is crucial for writing effective VBA code. This lesson covers all three categories of VBA operators:
Arithmetic operators perform mathematical operations on numerical values. They form the basis of calculations in your VBA programs.
| Operator | Description | Example | Result |
|---|---|---|---|
| ^ | Exponentiation (power of) | 3 ^ 2 |
9 |
| * | Multiplication | 5 * 4 |
20 |
| / | Division (floating-point) | 10 / 3 |
3.333... |
| \ | Integer division (discards remainder) | 10 \ 3 |
3 |
| Mod | Modulus (division remainder) | 10 Mod 3 |
1 |
| + | Addition or string concatenation | "Hello " + "World" |
"Hello World" |
| & | String concatenation (recommended) | "Total: " & 100 |
"Total: 100" |
Sub CalculateDiscount()
Dim originalPrice As Double
Dim discountRate As Double
Dim finalPrice As Double
originalPrice = 150.99
discountRate = 0.15 ' 15% discount
' Calculate final price with discount
finalPrice = originalPrice * (1 - discountRate)
' Display result
MsgBox "Original Price: $" & originalPrice & vbCrLf & _
"Discount: " & discountRate * 100 & "%" & vbCrLf & _
"Final Price: $" & Round(finalPrice, 2)
End Sub
Comparison operators evaluate relationships between values and return True or False. They're essential for decision-making in your code.
| Operator | Description | 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 >= 3 |
True |
Sub EvaluateGrade()
Dim score As Integer
score = InputBox("Enter your score (0-100):")
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
Logical operators combine multiple conditions and return Boolean results. They're powerful tools for creating complex decision structures.
| Operator | Description | Example | Result |
|---|---|---|---|
| And | True if both conditions are true | (5 > 3) And (2 < 4) |
True |
| Or | True if either condition is true | (5 > 3) Or (2 > 4) |
True |
| Not | Reverses the logical result | Not (5 > 3) |
False |
| Xor | True if conditions are different | (5 > 3) Xor (2 < 4) |
False |
Sub CheckLoanApproval()
Dim creditScore As Integer
Dim annualIncome As Currency
Dim existingLoans As Integer
creditScore = 720
annualIncome = 85000
existingLoans = 2
' Check loan approval criteria
If creditScore >= 700 And annualIncome > 50000 And existingLoans < 3 Then
MsgBox "Loan Approved!"
Else
MsgBox "Loan Denied. Please contact our office for details."
End If
End Sub
Copyright ® 2020 Dr.Liew Voon Kiong . All rights reserved [Privacy Policy]
Contact: Facebook Page