VBA If Then Else Statements
Make decisions in your code with conditional logic and branching
Quick Reference
If Then: Execute code if condition is true
If Then Else: Choose between two code paths
ElseIf: Test multiple conditions sequentially
Select Case: Test one value against multiple cases
Basic If Then Statement
Execute code only when a condition is true.
Single Line Syntax:
Multi-Line Syntax (Recommended):
Example 1: Simple Condition
Example 2: String Comparison
If Then Else Statement
Execute one block of code if true, another if false.
Syntax:
Example 1: Pass/Fail
Example 2: Even/Odd Number
ElseIf Statement
Test multiple conditions in sequence until one is true.
Syntax:
Example 1: Letter Grade
Example 2: Age Category
Important: VBA evaluates conditions in order and stops at the first true condition. Order matters!
Comparison Operators
| Operator | Meaning | Example |
|---|---|---|
| = | Equal to | If x = 5 Then |
| <> | Not equal to | If x <> 0 Then |
| > | Greater than | If x > 10 Then |
| < | Less than | If x < 10 Then |
| >= | Greater than or equal | If x >= 5 Then |
| <= | Less than or equal | If x <= 5 Then |
Logical Operators
Combine multiple conditions in a single If statement.
AND Operator
All conditions must be true.
OR Operator
At least one condition must be true.
NOT Operator
Reverses the condition.
Combining Multiple Operators
Use parentheses to control evaluation order
Nested If Statements
Place If statements inside other If statements for complex logic.
Example: Grade with Bonus
Tip: Deep nesting can be hard to read. Consider using ElseIf or Select Case instead.
Select Case Statement
Cleaner alternative to multiple ElseIf statements when testing one variable against many values.
Syntax:
Example 1: Day of Week
Example 2: Grade Letter
Example 3: Range of Values
When to use Select Case: When testing one variable against multiple values. Much cleaner than many ElseIf statements!
IIf Function (Inline If)
Shorthand for simple If-Then-Else in a single line.
Syntax:
Example 1: Pass/Fail
Example 2: Discount Calculation
Warning: IIf evaluates BOTH true and false expressions. Can cause issues with division by zero or function calls with side effects.
Best Practices
Common Mistakes
❌ Using = for assignment in If
❌ Forgetting End If
❌ Wrong Order in ElseIf
Put most specific conditions first!