Excel like a finance pro.
VBA · Control flow
If ... Then ... Else
Runs code when a condition is true, with optional ElseIf and Else branches.
When to use it
If ... Then runs code when a condition is true, with ElseIf for further tests and Else for everything else. Single-line If works for one statement; block If needs End If.
The code
- Code
If total > 1000 Then status = "Large" ElseIf total > 100 Then status = "Medium" Else status = "Small" End If
Worked examples
Multi-branch
If total > 1000 Then status = "Large" ElseIf total > 100 Then status = "Medium" Else status = "Small" End If → Three-way classification
Order the tests from most to least specific.
Single line
If found Then Exit Sub → One statement, no End If
Single-line form.
Object check
If Not rng Is Nothing Then rng.Select → Tests an object before using it
The Nothing check.
Worth knowing
- And and Or evaluate both sides, so If x > 0 And 1 / x > 2 still divides by zero when x is 0; nest the Ifs.
- Select Case reads better for many branches on one value.
- IIf(cond, a, b) is the inline version but evaluates both a and b.
Where it goes wrong
- Single-line If with several statements needs colons and is hard to read.
- Comparing strings is case sensitive unless Option Compare Text is set.
Related
Learn the moves here — or let Wauvel run them on your numbers.
Meet your AI CFO →One CFO-grade Excel tip a week
A short, practical email for finance operators — functions, shortcuts, and the moves that save an afternoon. Free, unsubscribe anytime.