Every macro you write will fail at some point. A file gets moved, a sheet gets renamed, a column arrives as text instead of numbers. The question is not whether that happens but what happens next: does the macro stop with a cryptic dialog and a Debug button that throws your colleague into the code editor, or does it say clearly what is wrong? And, far more dangerous, does it carry on and produce a report with a wrong number that nobody notices?
This lesson is for Excel users who write or maintain VBA, from the first recorded macro to tools a whole team depends on. You will learn the three kinds of error VBA knows, how each one is found, and why the quiet one is the expensive one. The worked example is a macro you can keep: ColumnHealthCheck from the free lesson above, which audits a column and tells you how many values are real numbers, how many are numbers stored as text, how much is blank and what the honest sum and average are.
All data in this article comes from the Error Demo sheet that the lesson's helper function builds: eight fictional January 2025 sales with the kind of mess every real export contains. The numbers are made up for practice; the trap they demonstrate is real.
The three kinds of error
VBA errors come in exactly three kinds, and each is found in a different place. Compile errors mean the code is not valid VBA: an If without an End If, a Next without a For, a misspelled keyword or, with Option Explicit on, a variable that was never declared. The editor refuses to run the procedure until you fix it, which is annoying but cheap.
Run-time errors happen in code that is perfectly valid but meets a reality it did not expect: division by zero (error 11), a sheet name that does not exist (error 9, subscript out of range), an object variable that was never set (error 91), a value of the wrong type (error 13, type mismatch). Excel stops, shows the number and a short message, and if you click Debug the offending line is highlighted in yellow. You know where it happened, which is most of the battle.
Logic errors are the third kind, and the only dangerous one. The code compiles, runs to the end and produces a result. The result is wrong. There is no message, no number and no yellow line. You find logic errors only by watching the code run, checking intermediate values and comparing the output with a number you worked out another way.
Worked example: the column that lies about its average
Run ColumnHealthCheck from the lesson. If the workbook has no sheet called Error Demo, the helper function DemoSheet creates one and fills column C with eight amounts. Two of them are written with a leading apostrophe, which makes Excel store them as text, exactly what a CSV import or a copy from a web page produces. One is the word pending and one is empty:
| Row | Date (A) | Customer (B) | Amount (C) | Stored as | Counted by the macro as |
|---|---|---|---|---|---|
| 2 | 01 Jan 2025 | Customer 1 | 1200.5 | Number | Real number |
| 3 | 02 Jan 2025 | Customer 2 | 940 | Number | Real number |
| 4 | 03 Jan 2025 | Customer 3 | 1050.75 | Text | Number as text |
| 5 | 04 Jan 2025 | Customer 4 | 380.25 | Number | Real number |
| 6 | 05 Jan 2025 | Customer 5 | (empty) | Empty | Blank |
| 7 | 06 Jan 2025 | Customer 6 | 610 | Number | Real number |
| 8 | 07 Jan 2025 | Customer 7 | pending | Text | Other text |
| 9 | 08 Jan 2025 | Customer 8 | 1499.9 | Text | Number as text |
On screen, rows 4 and 9 look like ordinary amounts. Excel usually shows a small green triangle in the corner of such a cell, and by default text is aligned to the left while numbers are aligned to the right, but nobody checks alignment in a long column. The macro checks properly: VarType(cell.Value) = vbString asks what is really stored, and IsNumeric separates text that looks like a number from real text such as pending.
Now the trap. Many reporting macros calculate an average like this: Application.Sum of the range divided by Application.CountA of the same range. Sum skips text, so it adds only the four real numbers: 1,200.50 + 940 + 380.25 + 610 = 3,130.75. CountA counts every non-empty cell, including the two text numbers and pending, so it returns 7. The average comes out as 3,130.75 รท 7 = 447.25. No error, no warning, and the figure is wrong whichever average you meant.
In the worksheet you can reproduce all of this with ordinary formulas: =SUM(C2:C9) returns 3,130.75, =COUNTA(C2:C9) returns 7, =COUNT(C2:C9) returns 4 and =AVERAGE(C2:C9) returns 782.69, because AVERAGE ignores text in a range just like SUM does. Convert the two text cells into real numbers and the average of the six amounts becomes 946.90.
| Calculation | Excel formula | VBA | Result |
|---|---|---|---|
| Sum รท non-empty cells (the trap) | =SUM(C2:C9)/COUNTA(C2:C9) | Application.Sum(r) / Application.CountA(r) | 447.25 |
| Average of real numbers | =AVERAGE(C2:C9) | total / numbers in ColumnHealthCheck | 782.69 |
| Average after converting the text numbers | =AVERAGE(C2:C9) after the fix | Same code, run again | 946.90 |
That is the nature of a logic error. The fix is one line, using Count instead of CountA and guarding the division, but you only write that line if you know the problem exists. The safe version of the snippet from the lesson looks like this:
Dim total As Double
Dim numbers As Long
total = Application.Sum(ws.Range("C2:C9"))
numbers = Application.Count(ws.Range("C2:C9")) ' counts numbers only
If numbers = 0 Then
MsgBox "No numeric values in C2:C9.", vbExclamation
Else
MsgBox "Average of " & numbers & " values: " & Format(total / numbers, "#,##0.00")
End If
It reports Average of 4 values: 782.69, and the count in the message is itself a warning: anyone who knows the column has eight rows will ask where the other four went. ColumnHealthCheck goes further and names the problem in its message: Warning: 2 value(s) look like numbers but are stored as text.
Step by step: catch each kind of error in the VBA editor
- Switch on Require Variable Declaration. In the editor (
Alt+F11) choose Tools โ Options โ Editor and tick Require Variable Declaration. New modules will start withOption Explicit. Add the line by hand to every existing module. - Compile before you run. Debug โ Compile VBAProject checks every module, not just the procedure you are about to run. If the menu item is greyed out, the project is already compiled and clean.
- Read a run-time error before you click. Note the number and message. Debug highlights the failing line; End stops the macro. Hover over the variables in the yellow line to see their values.
- Set a breakpoint. Click in the grey margin to the left of a line, or put the cursor on it and press
F9. A red dot appears. Run the macro withF5; it pauses there. - Step through. Press
F8to run one line at a time.Shift+F8steps over a call without going into it,Ctrl+Shift+F8runs to the end of the current procedure, andF5continues to the next breakpoint. - Print what the code sees. Open the Immediate window with
Ctrl+Gand add aDebug.Printline inside the loop, as shown below. Type?totaland pressEnterwhile paused to see a value on demand. - Watch all variables at once. View โ Locals Window lists every variable of the paused procedure with its value and type, updated after each step.
- Stop a runaway macro.
Ctrl+Break(on some laptopsEscorFnplus a key) interrupts a running macro and offers Debug. - Check the result another way. Compare the macro's number with a worksheet formula, such as
=AVERAGE(C2:C9). If they disagree, one of them has a logic error, and now you know where to start.
This loop prints the address, the stored type and the value of every cell, which exposes the text numbers in one glance:
Dim cell As Range
For Each cell In ws.Range("C2:C9")
Debug.Print cell.Address, TypeName(cell.Value), cell.Value
Next cell
In the Immediate window, rows 4 and 9 show String where the others show Double, row 6 shows Empty, and row 8 shows String next to pending. That single listing turns an invisible logic error into a visible one.

Common mistakes and how to spot them
- No
Option Explicit. A typo liketotl = totl + cell.Valuesilently creates a new, empty variable, and the report shows 0. Spot it: the first line of the module is notOption Explicit. - Dividing by a count of the wrong thing.
CountAcounts text,Countcounts numbers. Spot it: compare the count with the number of values you think you added; in the demo 7 against 4. - Hard-coded last rows.
Range("C2:C1000")silently ignores row 1001 and everything after it. Spot it: search for large row numbers in range addresses and replace them withws.Cells(ws.Rows.Count, "C").End(xlUp).Row. - Unguarded division. An empty input makes the count 0 and the macro dies with error 11, division by zero. Spot it: every
/whose divisor can be 0 needs anIfin front. On Error Resume Nextat the top of a procedure. It hides every run-time error that follows, so the macro reports success with wrong data. Spot it: the statement is not followed within a few lines byOn Error GoTo 0.- Debugging by MsgBox. A message box inside a 500-row loop means 500 clicks. Spot it: if you find yourself pressing
Enterrepeatedly, replace it withDebug.Print. - Testing only on clean data. A macro that has never seen text numbers, blanks and words in a numeric column has not been tested. Spot it: build a demo sheet like Error Demo with the worst data you can imagine and run every macro against it.
Quick reference: debugging keys, functions and error numbers
| Item | Key or code | What it does |
|---|---|---|
| Compile project | Debug โ Compile VBAProject | Finds compile errors in every module |
| Run / continue | F5 | Runs the procedure or continues after a pause |
| Step into / over / out | F8 / Shift+F8 / Ctrl+Shift+F8 | One line at a time, skipping or leaving called procedures |
| Toggle breakpoint | F9 | Pauses the macro on that line |
| Immediate window | Ctrl+G | Shows Debug.Print output; ?expr evaluates |
| Interrupt | Ctrl+Break | Stops a running macro |
| Stored type | VarType(v), TypeName(v) | What is really in a cell: vbString, Double, Empty |
| Looks numeric? | IsNumeric(v) | True for numbers and text that can be read as a number |
| Worksheet counts | =COUNT() / =COUNTA() | Numbers only / every non-empty cell |
| Error 9 | Subscript out of range | Name or index not in the collection |
| Error 11 / 13 | Division by zero / Type mismatch | Guard the divisor / check the type |
| Error 91 | Object variable not set | An object was used before Set |
Real-world uses
- Checking an import before it reaches the report. Run a health check on every numeric column after loading a CSV and stop the process if any value is stored as text, instead of discovering the problem in a board meeting.
- Month-end reconciliation. A macro totals invoices and compares them with the ledger. Stepping through it with a breakpoint on the first mismatch shows exactly which invoice causes the difference.
- Inherited macros. You take over a tool nobody understands.
Debug โ Compile VBAProject, thenOption Explicitin every module and a compile again, usually reveals a handful of undeclared or misspelled variables within minutes. - Overnight or scheduled jobs. A macro that runs while nobody watches cannot ask questions. Error handlers and a log file, which the second half of this course covers, are what tell you the next morning what went wrong.
- Tools for colleagues. A clear message such as There is no sheet called Data saves a phone call. A technical error dialog with a Debug button usually does not.
What you will build in the rest of this course
This first lesson is free. Lessons 2 to 8 are part of the full course, a one-time purchase of $9.90. The first three teach you to find logic errors by watching the code; the last four teach you to handle run-time errors so users never see the debug dialog.
Breakpoints and Stepping. You slow a macro down to human speed, walk through it line by line, drag the yellow arrow to repeat or skip lines, and set a breakpoint that only fires on the one row out of thousands you care about.
The Immediate Window and Debug.Print. You use the Immediate window as a scratchpad, ask questions with ?, leave a scrollable trail with Debug.Print and stop the macro automatically with Debug.Assert when something you were sure of turns out false.
The Locals and Watch Windows. You see every variable at once, drill into objects such as a worksheet, and let a watch expression pause the macro at the exact moment a value goes wrong.
On Error GoTo: Catching Failures. You replace the technical error dialog with your own message, learn the three-part shape of a handled procedure and use the Err object to report what happened.
On Error Resume Next, Used Carefully. You learn the narrow cases where ignoring an error is right, how to check Err.Number straight after a risky line and why the scope of the statement is the whole procedure.
Cleanup Patterns That Never Leak. You make sure screen updating, calculation mode and events are always restored, even when the macro crashes halfway, with a single exit that every path passes through.
Raising and Logging Your Own Errors. You signal business problems such as an empty input sheet with Err.Raise and write every failure to a log file, so a problem at night leaves a trail in the morning.
Summary
VBA knows three kinds of error. Compile errors are caught before the code runs, especially with Option Explicit and Debug โ Compile VBAProject. Run-time errors stop the macro with a number and a yellow line. Logic errors say nothing: in the demo column, Sum รท CountA reports an average of 447.25 when the four real numbers average 782.69, simply because two amounts are stored as text. You find logic errors by stepping through the code, printing what it sees and checking results against a second calculation.
Try it now in the lesson above: run ColumnHealthCheck on the demo sheet, then point it at a column of your own data and see whether everything that looks like a number really is one. Then answer the check question on the Sum and CountA trap.
Frequently asked questions
What are the three types of errors in VBA?
Compile errors, where the code is not valid VBA; run-time errors, where valid code fails while running, such as division by zero; and logic errors, where the code runs but gives the wrong result.
How do I debug a macro step by step in Excel?
Open the VBA editor with Alt+F11, click inside the macro and press F8. Each press runs one line and highlights the next one in yellow, so you can check values as you go.
What does Option Explicit do in VBA?
It forces you to declare every variable with Dim before using it. A misspelled variable name then causes a compile error instead of silently creating a new, empty variable.
Why does SUM ignore some numbers in my Excel column?
Those cells hold numbers stored as text, often from a CSV import or a copy from a web page. SUM and AVERAGE skip text in a range, while COUNTA counts it.
Where do I see Debug.Print output?
In the Immediate window of the VBA editor, which you open with Ctrl+G. You can also type a question such as ?ActiveSheet.Name there and press Enter.
How do I stop a macro that is running too long?
Press Ctrl+Break, or Esc on many keyboards, and choose Debug or End in the dialog that appears. On laptops without a Break key, a combination with Fn usually works.
Keep going: Errors & Debugging
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.
- Breakpoints and Stepping
- The Immediate Window and Debug.Print
- The Locals and Watch Windows
- On Error GoTo: Catching Failures
- On Error Resume Next, Used Carefully
- Cleanup Patterns That Never Leak
- Raising and Logging Your Own Errors