Why decisions are where macros get smart
A macro without decisions is a tape recorder: it plays the same steps on every row, whatever the row contains. Real data does not cooperate with that. Some orders are large, some are small, some amounts are missing and some cells hold an error from a broken lookup in someone else's system. The moment your code has to treat those rows differently, you need If. It is the statement that lets a macro look at a value and choose what to do, and it is the first thing to learn in the Logic & Loops course.
This free first lesson is for people who can already run a simple macro and now want it to react to the data. Think of the analyst who colours overdue invoices, the accountant who sorts transactions into categories, or the team assistant who checks a sign-up list for missing entries. The macro in the lesson above, ClassifyOrders, creates fourteen fictional orders, deliberately leaves two amounts blank and breaks one with #N/A, and then labels each row. This article walks through the same example: how an If chain is read, why the order of the tests matters, how to protect your code from blanks and errors, and how to check the result with ordinary worksheet formulas.
The concept: the first true branch wins
An If statement has a condition, a block of code, and an End If. The condition is any expression that comes out True or False, such as amount > 3000. When the condition is True, VBA runs the indented block; when it is False, VBA skips it. Else adds a block for everything the condition missed, and ElseIf adds further tests in between. VBA reads the chain from top to bottom, runs the first branch whose condition is True, and then jumps straight to End If without even looking at the remaining tests.
If amount > 8000 Then
label = "Key account"
ElseIf amount > 3000 Then
label = "Large"
ElseIf amount > 0 Then
label = "Standard"
Else
label = "Zero or negative"
End If
That single rule, first true branch wins, explains why the thresholds in the lesson run from the largest down. An amount of 9,600 is greater than 8,000, greater than 3,000 and greater than 0, so three conditions are true at once. Because the 8,000 test comes first, the row becomes a Key account and the other two tests never run. Put amount > 0 at the top instead, and every positive amount, however large, ends up as Standard. Nothing crashes, the macro simply produces a wrong report, which is the most expensive kind of bug.
For very short decisions VBA also allows a one-line form without End If: If amount > 8000 Then label = "Key account" Else label = "Other". It is handy for a single assignment, but as soon as a branch needs two statements or an ElseIf, use the block form. It is easier to read, easier to extend, and the indentation shows at a glance which lines belong to which branch.
The guard clauses: test what a value is before what it says
The lesson macro does not start with a number. It starts with two questions about the kind of value in the cell. IsError(cell.Value) is True for #N/A, #REF!, #DIV/0! and the other error values. IsEmpty(cell.Value) is True for a cell that has never held anything. Only when both are False does the code copy the value into the numeric variable amount and start comparing.
The order is not cosmetic. A blank cell used in a numeric comparison quietly behaves like zero, so without the IsEmpty test the two missing amounts would be labelled Zero or negative and disappear among genuine credit notes. An error value is worse: comparing it with a number stops the macro with run-time error 13, Type mismatch, and the message does not tell you which row caused it. With the guards in front, both situations become branches you chose, with their own labels, and the macro counts them in problems so the closing message can say how many rows need a human.
If IsError(cell.Value) Then
label = "Check the source"
problems = problems + 1
ElseIf IsEmpty(cell.Value) Then
label = "Missing amount"
problems = problems + 1
Else
amount = cell.Value
If amount > 8000 Then
label = "Key account"
ElseIf amount > 3000 Then
label = "Large"
ElseIf amount > 0 Then
label = "Standard"
Else
label = "Zero or negative"
End If
End If
Notice the nesting: the numeric chain lives inside the outer Else and is indented one level further. Each If has its own End If, and the indentation is what lets you see which one closes which. If an export might also contain text where a number belongs, add ElseIf Not IsNumeric(cell.Value) Then as a third guard before the outer Else, exactly as the trap section of the lesson shows.
The worked example: fourteen orders, six labels
Here is what ClassifyOrders writes into its new sheet. The amounts come from a small formula inside the macro, 900 * i - 1500 * (i Mod 3), so they look irregular, every fifth row is left blank, and row 8 receives the formula =NA() to imitate a broken lookup. Column C is filled by the decision chain.
| Row | A: Order | B: Amount | C: Class (written by VBA) |
|---|---|---|---|
| 2 | ORD-001 | β600.00 | Zero or negative |
| 3 | ORD-002 | β1,200.00 | Zero or negative |
| 4 | ORD-003 | 2,700.00 | Standard |
| 5 | ORD-004 | 2,100.00 | Standard |
| 6 | ORD-005 | (blank) | Missing amount |
| 7 | ORD-006 | 5,400.00 | Large |
| 8 | ORD-007 | #N/A (formula =NA()) | Check the source |
| 9 | ORD-008 | 4,200.00 | Large |
| 10 | ORD-009 | 8,100.00 | Key account |
| 11 | ORD-010 | (blank) | Missing amount |
| 12 | ORD-011 | 6,900.00 | Large |
| 13 | ORD-012 | 10,800.00 | Key account |
| 14 | ORD-013 | 10,200.00 | Key account |
| 15 | ORD-014 | 9,600.00 | Key account |
You can check the macro with ordinary worksheet formulas. That is not distrust, it is good practice: when two independent methods agree, you can hand the report on with confidence. The nested IF formula below follows the same order as the VBA chain, including the guards, and returns the same label for every row. Excel's IF only evaluates the branch it needs, so ISERROR in front protects the comparisons just as it does in the macro.
| Check | Formula | Result |
|---|---|---|
| Label for row 2, fill down to row 15 | =IF(ISERROR(B2),"Check the source",IF(ISBLANK(B2),"Missing amount",IF(B2>8000,"Key account",IF(B2>3000,"Large",IF(B2>0,"Standard","Zero or negative"))))) | same as column C |
| Key accounts | =COUNTIF(C2:C15,"Key account") | 4 |
| Amounts above 8,000 | =COUNTIF(B2:B15,">8000") | 4 |
| Blank amounts | =COUNTBLANK(B2:B15) | 2 |
| Error values | =SUMPRODUCT(--ISERROR(B2:B15)) | 1 |
| Rows flagged for a human | =COUNTIF(C2:C15,"Missing amount")+COUNTIF(C2:C15,"Check the source") | 3 |
The message box at the end of the macro reads Classified 14 orders, 3 of them flagged for a human. The chart below puts the fourteen amounts next to the two thresholds, so you can see why each bar received its colour. The gaps are the rows the guards caught before any comparison could go wrong.
Step by step: run it and watch the decisions in Excel
Reading code is good, watching it decide is better. These steps run the lesson macro and then let you follow one row through the chain. They work in desktop Excel for Windows and Mac.
- Open a new workbook, press
Alt+F11(Mac: Tools β Macro β Visual Basic Editor) and choose Insert β Module. - Paste the
ClassifyOrdersmacro from the lesson above. Check thatOption Explicitis the first line of the module. - Click inside the macro and press
F5. Switch to Excel: a new sheet named Orders plus the time holds the fourteen rows and their labels, and the message box reports 3 flagged rows. - Back in the editor, click on the line
If IsError(cell.Value) Thenand pressF9. A dark red dot marks the breakpoint. - Press
F5again. The macro builds a fresh sheet and stops at the breakpoint with the line highlighted in yellow. - Press
F8repeatedly. Watch the yellow line jump: for ORD-001 it skips both guards, enters the inner chain and lands on Zero or negative. Hover the mouse overamountto see -600. - Open View β Locals Window to see
i,amount,labelandproblemschange as you step. Whenireaches 6 (ORD-005), the yellow line stops atElseIf IsEmptyand the numeric chain is never entered. - Press
F5to let the rest run, or click the square Reset button to stop. Remove the breakpoint withF9on the same line. - Now experiment: move
ElseIf amount > 0 Thenabove the 8,000 test, run again and compare the two sheets. Every positive amount is now Standard.
If isDone = True Then compares once too often. Write If isDone Then, and If Not isDone Then for the opposite case. The same applies to functions that return True or False, such as IsEmpty and IsError.
A look ahead: And does not short-circuit
Many people try to squeeze the guard and the comparison into one line: If Not IsError(cell.Value) And cell.Value > 0 Then. In several other languages that would be safe, because the second half is skipped when the first is False. VBA evaluates both sides of And and Or every time, so the comparison still meets the #N/A and the macro still stops with a type mismatch. The fix is the structure you saw above: a separate If or ElseIf for each guard. The next lesson, Building Conditions, covers And, Or and Not in detail, and the Select Case lesson shows a tidier way to write long threshold chains:
Select Case amount
Case Is > 8000
label = "Key account"
Case Is > 3000
label = "Large"
Case Is > 0
label = "Standard"
Case Else
label = "Zero or negative"
End Select
Common mistakes and how to spot them
These are the decision bugs that turn up most often in real macros, with the symptom that gives each one away.
- Thresholds in the wrong order. The smallest test at the top catches everything. Symptom: one label suddenly dominates the report. Fix: order from most specific to least specific, usually largest to smallest.
- No guard for blank cells. Blanks behave like zero in a comparison. Symptom: missing data shows up as small or zero values instead of being reported. Fix:
IsEmptybefore any numeric test. - No guard for error values. Symptom: run-time error 13, Type mismatch, on a comparison that looks perfectly correct. Fix:
IsErroras the very first test. - Combining the guard with And. Symptom: the same type mismatch even though you wrote
Not IsError(β¦) And β¦. Fix: separateIforElseIfbranches. - A missing or misplaced End If. Symptom: a compile error such as Block If without End If or End If without block If. Fix: indent every block consistently and count the pairs.
- Using = where you meant a range of values.
If amount = 3000matches exactly 3,000 only. Symptom: rows that never match. Fix: use>,>=,<or<=. - Case-sensitive text tests. By default VBA compares text exactly, so
If region = "north"does not match North. Symptom: text conditions that fail on some rows. Fix: compareLCase(region) = "north", or putOption Compare Textat the top of the module.
Quick reference: decisions in VBA and in the worksheet
The keywords, functions and shortcuts used in this lesson:
| Item | Kind | What it does |
|---|---|---|
If β¦ Then β¦ End If | VBA | Run a block only when a condition is True |
ElseIf / Else | VBA | Further tests / everything that is left |
=, <>, >, >=, <, <= | Operators | Comparisons that return True or False |
IsError, IsEmpty, IsNumeric | VBA functions | Test the kind of value before comparing it |
Select Case | VBA | A tidier form of a long chain on one value |
IF | Worksheet function | The formula version of a decision |
ISERROR, ISBLANK | Worksheet functions | The formula versions of the guards |
COUNTIF, COUNTBLANK, SUMPRODUCT | Worksheet functions | Check the macro's counts independently |
F8 | Shortcut (editor) | Run one line at a time and watch which branch is taken |
F9 | Shortcut (editor) | Set or remove a breakpoint |
Ctrl+G | Shortcut (editor) | Immediate window, e.g. ?IsEmpty(Range("B6").Value) |
Real-world uses
The same pattern, guard first and then a chain of thresholds, appears in all kinds of everyday Excel work:
- Credit control. Label every open invoice as current, 30 days, 60 days or over 90 days past due, with a separate label for invoices whose due date is missing.
- Order triage. Mark orders above an approval limit for a manager, route small orders straight through, and flag negative amounts as possible credit notes, exactly like the lesson.
- Data quality checks. Before a monthly upload, walk through an export and label rows with errors, blanks or text in numeric columns, then count them so the person responsible knows how much cleaning is needed.
- Stock levels. Compare quantity on hand with a reorder point and label each item as reorder now, watch or fine, with a guard for items whose quantity cell is empty.
- Grading and scoring. Turn scores into bands such as fail, pass, merit and distinction, from the highest band downwards so every score lands in exactly one band.
What you will build in the rest of this course
This first lesson is free. The remaining seven lessons are part of the full Logic & Loops course, a one-time purchase of $9.90, and they turn today's single decision into macros that process whole files:
Building Conditions. Combine tests with And, Or and Not, compare text and dates safely, and learn why VBA evaluates both sides of And, with a pattern that keeps guards and comparisons apart.
Select Case. Rewrite long ElseIf chains as readable Select Case blocks, using ranges such as Case 3001 To 8000, lists of values and Case Is comparisons.
For ... Next. The loop that walked the rows in today's macro, explained properly: counters, Step, counting backwards when you delete rows, and sizing a loop from the data instead of a fixed number.
For Each. Loop over every cell of a range or every sheet of a workbook without managing a counter, and know when For Each is the clearer choice.
Do While and Do Until. Repeat work when you cannot count the repetitions in advance, for example until the first empty row, and avoid the endless loop that freezes Excel.
Exit, Guard Clauses and Skipping. Leave a loop or a procedure early, skip rows that should not be processed, and structure code so the unusual cases are handled first and the main work stays readable.
Nested Loops Over Rows and Columns. Put one loop inside another to process a whole table cell by cell, row by row and column by column, and keep it fast enough for real files.
Summary
If, ElseIf and Else let a macro choose what to do with each value. VBA runs the first branch whose condition is True and skips the rest, so order thresholds from the most specific to the least. Before comparing numbers, test what kind of value you have: IsError first, then IsEmpty, then IsNumeric if text is possible. Keep those guards as separate branches, because And evaluates both sides, and confirm the macro's results once with worksheet formulas such as COUNTIF.
Scroll back up, run ClassifyOrders, then add ElseIf amount > 20000 Then label = "Strategic" in the right place and see whether any row changes. Then step through one row with F8: once you have watched the yellow line skip the branches it does not need, the first true branch rule will stay with you for good.
Frequently asked questions
How does If ElseIf Else work in VBA?
VBA checks the conditions from top to bottom and runs the block of the first one that is True, then jumps to End If. Else runs only when none of the conditions was True.
Do I always need End If in VBA?
A block If that spans several lines must end with End If. Only the single-line form, such as If x > 0 Then y = 1, is written without it.
Why do I get a type mismatch error in my If statement?
Usually the cell holds an error value such as #N/A, or text, and the code compares it with a number. Test IsError and IsNumeric before the comparison.
How do I check if a cell is empty in VBA?
Use IsEmpty(Range("B2").Value), which returns True for a cell that has never held a value. A cell containing a formula that returns "" is not empty, so compare with "" in that case.
Does VBA short-circuit And and Or?
No. VBA evaluates both sides of And and Or, so a guard and a risky comparison on the same line can still raise an error. Put the guard in its own If or ElseIf.
When should I use Select Case instead of ElseIf?
Use Select Case when every test looks at the same value, such as an amount or a region, because it is easier to read. Keep If and ElseIf when the tests check different things.
Keep going: Logic & Loops
This free lab is lesson 1 of 8. Unlock the other 7 hands-on labs, the final exam and your certificate for a one-time β¬9.90.
- Building Conditions
- Select Case
- For ... Next
- For Each
- Do While and Do Until
- Exit, Guard Clauses and Skipping
- Nested Loops Over Rows and Columns