VBA course · Lesson 8 of 33
Making decisions: If, ElseIf and Select Case
Teach your macros to decide: If...Then...Else, ElseIf chains, And/Or conditions, single-line If and Select Case with ranges and Case Is.
So far every macro you have written runs the same lines from top to bottom, every time. Real work is rarely that simple. An invoice is either paid or not. A sales figure is above target or below it. A staff member is in one department or another. To handle these situations a macro must make decisions: run some lines only when a condition is true, and other lines when it is false.
VBA gives you two tools for this. The If statement checks one or more conditions and picks a path. The Select Case statement compares one value against a list of possibilities and is often tidier when there are many options. This lesson covers both, with the mistakes that trip up almost every beginner.
The basic If...Then...End If
The simplest form runs a block of code only when a condition is true:
Option Explicit
Sub FlagLargeOrder()
Dim amount As Double
amount = Range("B2").Value
If amount > 1000 Then
Range("B2").Font.Color = vbRed
Range("C2").Value = "Check with manager"
End If
End SubRead it like an English sentence: if the amount is more than 1000, then colour it red and write a note. The condition amount > 1000 is an expression that is either True or False. When it is True, every line between Then and End If runs. When it is False, VBA jumps straight past End If and carries on.
Notice the indentation. VBA does not care about it, but people do: indenting the lines inside the If by four spaces makes it obvious which lines belong to the decision.
If...Else: two paths
Often you want one thing when the condition is true and something else when it is false. Add an Else branch:
Option Explicit
Sub InvoiceStatus()
Dim amountDue As Double
amountDue = Range("D2").Value
If amountDue = 0 Then
Range("E2").Value = "Paid"
Range("E2").Interior.Color = RGB(198, 239, 206) ' light green
Else
Range("E2").Value = "Open"
Range("E2").Interior.Color = RGB(255, 199, 206) ' light red
End If
End SubExactly one of the two blocks runs, never both and never neither.
ElseIf: more than two paths
When there are several possible outcomes, chain them with ElseIf. VBA tests the conditions from the top down and runs the first block whose condition is true. The rest are skipped, even if they would also be true.
Option Explicit
Sub SetCommission()
Dim sales As Double
Dim rate As Double
sales = Range("B2").Value
If sales >= 50000 Then
rate = 0.08
ElseIf sales >= 25000 Then
rate = 0.05
ElseIf sales >= 10000 Then
rate = 0.03
Else
rate = 0
End If
Range("C2").Value = rate
Range("D2").Value = sales * rate
End SubThe order matters. If you tested sales >= 10000 first, a salesperson with 60,000 would match that line, get 3% and never reach the 8% test. With "greater than or equal" bands, always start with the highest threshold and work down (or the lowest with "less than", working up).
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Rep | Sales | Rate | Commission |
| 2 | Maria Lopez | 32500 | 5% | 1625 |
Before and after running SetCommission on a row with 32,500 in sales (C2 formatted as %)
Note that it is ElseIf, one word. Writing Else If with a space starts a brand new nested If inside the Else, which then needs its own End If, and you get a confusing "Block If without End If" compile error.
Combining conditions with And, Or, Not
A condition can combine several tests:
And: true only when both sides are true.If region = "North" And sales > 20000 ThenOr: true when at least one side is true.If status = "Overdue" Or status = "Disputed" ThenNot: flips true to false.If Not IsEmpty(Range("A2")) Then
When you mix And and Or, use brackets to make your intention clear. And is evaluated before Or, just like multiplication before addition, so a Or b And c means a Or (b And c). Brackets cost nothing and prevent bugs.
Option Explicit
Sub CheckBonus()
Dim dept As String
Dim yearsService As Long
Dim rating As Long
dept = Range("B2").Value
yearsService = Range("C2").Value
rating = Range("D2").Value
' Bonus for good ratings in Sales, or for anyone with 10+ years and a rating of 4+
If (dept = "Sales" And rating >= 4) Or (yearsService >= 10 And rating >= 4) Then
Range("E2").Value = "Bonus"
Else
Range("E2").Value = "-"
End If
End SubAnd and Or, even when the first side already decides the answer. So If qty <> 0 And total / qty > 10 Then still crashes with "Division by zero" when qty is 0. Split such checks into two nested If statements. See Operators and expressions in VBA for more on this.The single-line If
For a very short decision you can write the whole thing on one line, with no End If:
Option Explicit
Sub ClearNegative()
If Range("B2").Value < 0 Then Range("B2").Value = 0
End SubThis is handy for tiny guards, but keep it to one action. You can add Else on the same line or several statements separated by colons, but such lines quickly become hard to read. The moment you need two actions, use the block form.
Nested If statements
You can put an If inside another If. This is useful when the second question only makes sense after the first has been answered:
Option Explicit
Sub CheckInvoice()
Dim paid As Boolean
Dim dueDate As Date
paid = (Range("C2").Value = "Yes")
If Not paid Then
dueDate = Range("D2").Value
If dueDate < Date Then
Range("E2").Value = "OVERDUE"
Else
Range("E2").Value = "Not yet due"
End If
Else
Range("E2").Value = "Paid"
End If
End SubEach If needs its own End If, and good indentation shows which one closes which. If you find yourself three or four levels deep, it is usually a sign that ElseIf or Select Case would be clearer.
Select Case: choosing from many values
When you keep comparing the same value against many options, Select Case is cleaner than a long ElseIf chain. You name the value once at the top and list the cases below:
Option Explicit
Sub AssignManager()
Dim region As String
Dim manager As String
region = Range("B2").Value
Select Case region
Case "North"
manager = "Anna Berg"
Case "South", "South-East"
manager = "Luis Ortega"
Case "West"
manager = "Priya Shah"
Case Else
manager = "Unassigned"
End Select
Range("C2").Value = manager
End SubA comma-separated list ("South", "South-East") means "any of these". Case Else catches everything not matched above; always include it, even if it only writes a warning, so unexpected data does not slip through silently.
Ranges and comparisons in Select Case
Select Case works with numbers too, and has two special forms: Case 1 To 5 for an inclusive range, and Case Is >= 90 for a comparison.
Option Explicit
Sub GradeScore()
Dim score As Double
Dim grade As String
score = Range("B2").Value
Select Case score
Case Is >= 90
grade = "A"
Case 80 To 89.99
grade = "B"
Case 70 To 79.99
grade = "C"
Case 0 To 69.99
grade = "F"
Case Else
grade = "Invalid score"
End Select
Range("C2").Value = grade
End SubLike ElseIf, only the first matching case runs. A neat trick for testing several unrelated conditions is Select Case True, where each Case is a full condition: Case sales > 50000 And region = "North". Use it sparingly; a plain If chain is usually easier for others to read.
Text comparisons are case-sensitive
By default "north" = "North" is False in VBA, because comparisons are binary (they look at exact character codes). If users type data by hand, protect yourself by converting both sides: If UCase(region) = "NORTH" Then. Alternatively put Option Compare Text at the very top of the module, which makes all text comparisons in that module ignore case. Trailing spaces are another invisible cause of failed matches; Working with text (strings) in VBA shows how to clean them with Trim.
Applying a decision to every row
A decision on one cell is only the start. Combined with a loop (explained fully in For loops: For...Next and For Each), the same If runs on every row of a list:
Option Explicit
Sub MarkOverdue()
Dim r As Long
For r = 2 To 6
If Cells(r, 3).Value = "No" And Cells(r, 4).Value < Date Then
Cells(r, 5).Value = "OVERDUE"
Else
Cells(r, 5).Value = ""
End If
Next r
End SubCommon mistakes
- Forgetting
End If: the compiler reports "Block If without End If", often pointing at the end of the procedure rather than the real problem. Check that every multi-lineIfis closed. Else Ifinstead ofElseIf: see above.- Wrong order of ElseIf tests: a broad condition placed first swallows the narrower ones below it.
- Comparing a number stored as text: a cell containing the text
"1000"is not greater than 999 the way you expect. Convert withCDblorValfirst, or fix the data. - Empty cells: an empty cell compares as 0 with numbers and as
""with text, so a blank amount may count as "paid". Test withIsEmptyfirst when blanks are possible. - Writing
If x = 1 Or 2: this does not mean "x is 1 or 2". WriteIf x = 1 Or x = 2, or useSelect Case xwithCase 1, 2.
If statement. VBA's If controls which code runs; the worksheet IF returns a value inside a cell.Check yourself
1. An ElseIf chain tests sales >= 10000 first and sales >= 50000 second. What happens for sales of 60,000?
VBA stops at the first true condition, so the order of the tests decides the result.
2. Which line correctly tests whether status is "Overdue" or "Disputed"?
Each side of Or must be a complete comparison.
3. Which Select Case line matches every score from 80 up to 89?
The To keyword defines an inclusive range in a Case clause.
4. Why does If qty <> 0 And total / qty > 10 Then fail when qty is 0?
VBA has no short-circuit evaluation. Use two nested If statements instead.
5. What does Case Else do in a Select Case block?
Case Else is the catch-all branch, similar to Else in an If statement.