Tabellab

Three Kinds of Error

Lesson 1 of 8Reading

Not all bugs are the same

Before you can fix a problem you have to know what kind it is. VBA gives you exactly three, and each is found in a different way. Knowing which one you are looking at is the difference between a two-minute fix and a lost afternoon.

The three types

  • Compile errors โ€” the code is not valid VBA: a missing End If, a misspelled keyword, a Next without a For. Excel refuses to run anything until you fix it, so these cost minutes, not hours.
  • Run-time errors โ€” the code is valid but reality disagrees: dividing by zero, opening a file that has been moved, asking for Worksheets("Data") after somebody renamed the sheet. You get a yellow line and a number.
  • Logic errors โ€” the code runs perfectly and gives the wrong answer. No message, no yellow line, just an average quietly 15 per cent too low on a report you already sent.
  • Only the third kind is dangerous, because nothing tells you it happened.

A macro that hunts logic errors in your data

The macro below is the one to keep. Paste it into a standard module and run it. If there is no sheet called Error Demo it builds one, filled with the sort of messy column every real export contains, and audits it: how many values are real numbers, how many are numbers Excel is storing as text, how much is blank, and what the honest sum and average are. Later, change the sheet name in DemoSheet and point it at your own data.

Option Explicit

Sub ColumnHealthCheck()
    Dim ws As Worksheet
    Dim cell As Range
    Dim lastRow As Long
    Dim numbers As Long
    Dim textNumbers As Long
    Dim otherText As Long
    Dim blanks As Long
    Dim total As Double
    Dim msg As String

    Set ws = DemoSheet()
    lastRow = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row
    If lastRow < 2 Then
        MsgBox "Nothing to check in column C.", vbInformation
        Exit Sub
    End If

    For Each cell In ws.Range("C2:C" & lastRow)
        If Len(cell.Value) = 0 Then
            blanks = blanks + 1
        ElseIf VarType(cell.Value) = vbString Then
            If IsNumeric(cell.Value) Then
                textNumbers = textNumbers + 1
            Else
                otherText = otherText + 1
            End If
        Else
            numbers = numbers + 1
            total = total + cell.Value
        End If
    Next cell

    msg = "Column C on sheet " & ws.Name & ", rows 2 to " & lastRow & vbCrLf & vbCrLf & _
          "Real numbers:    " & numbers & vbCrLf & _
          "Numbers as text: " & textNumbers & vbCrLf & _
          "Other text:      " & otherText & vbCrLf & _
          "Blank cells:     " & blanks & vbCrLf & vbCrLf

    If numbers = 0 Then
        msg = msg & "No numeric values, so there is no average to report."
    Else
        msg = msg & "Sum:     " & Format(total, "#,##0.00") & vbCrLf & _
              "Average: " & Format(total / numbers, "#,##0.00")
    End If

    If textNumbers > 0 Then
        msg = msg & vbCrLf & vbCrLf & "Warning: " & textNumbers & " value(s) look " & _
              "like numbers but are stored as text. SUM and this total both skip them."
    End If

    MsgBox msg, vbInformation, "Column health check"
End Sub

Private Function DemoSheet() As Worksheet
    Dim ws As Worksheet
    Dim found As Worksheet
    Dim values As Variant
    Dim i As Long

    For Each ws In ThisWorkbook.Worksheets
        If ws.Name = "Error Demo" Then Set found = ws
    Next ws

    If Not found Is Nothing Then
        Set DemoSheet = found
        Exit Function
    End If

    Set found = ThisWorkbook.Worksheets.Add
    found.Name = "Error Demo"
    found.Range("A1:C1").Value = Array("Date", "Customer", "Amount")
    found.Range("A1:C1").Font.Bold = True

    ' The two entries starting with an apostrophe stay TEXT in the cell -
    ' exactly what a CSV import or a copy from a web page gives you.
    values = Array(1200.5, 940, "'1050.75", 380.25, "", 610, "pending", "'1499.9")

    For i = LBound(values) To UBound(values)
        found.Cells(i + 2, 1).Value = DateSerial(2025, 1, i + 1)
        found.Cells(i + 2, 2).Value = "Customer " & i + 1
        found.Cells(i + 2, 3).Value = values(i)
    Next i

    found.Columns("A:C").AutoFit
    Set DemoSheet = found
End Function

Line by line

  • Set ws = DemoSheet() โ€” the helper creates the sheet only if it is missing, so a second run duplicates nothing.
  • ws.Cells(ws.Rows.Count, "C").End(xlUp).Row โ€” walks up from the bottom to the last used cell in column C. Never hard-code a last row; a hard-coded 1000 is how reports silently lose row 1001 onward.
  • VarType(cell.Value) = vbString โ€” asks what Excel really stored. A cell showing 1050.75 may hold a number or text, and the two behave differently.
  • IsNumeric(cell.Value) separates text that looks numeric from real text such as pending.
  • If numbers = 0 โ€” the division guard. Division by zero is the commonest run-time error in reporting macros, and one line removes it.
  • The & _ ending a line is a continuation: space, underscore, new line. It is the only way to break a long VBA statement.

The trap: SUM and COUNT disagree

This is the hour you get back. When numbers arrive as text โ€” from a CSV, a web page, a system export โ€” Application.Sum ignores them while CountA counts them. Divide one by the other and the average is too low, with no error of any kind. The macro above warns you; the version below is what most people write.

' Looks perfectly reasonable. Quietly wrong.
Dim total As Double
Dim count As Long

total = Application.Sum(ws.Range("C2:C1000"))          ' skips text
count = Application.CountA(ws.Range("C2:C1000"))       ' counts text
MsgBox "Average: " & total / count                     ' too low, no warning

Compile the whole project before you run it

Put Option Explicit on the first line of every module. It forces you to declare every variable, so a typo like totl for total becomes a compile error instead of a permanently empty variable that makes your report wrong. Then choose Debug โ†’ Compile VBAProject: it checks the whole project rather than stopping at the first line that happens to run.

Tick Tools โ†’ Options โ†’ Require Variable Declaration in the VBA editor. It only adds Option Explicit to modules created after ticking it โ€” existing ones must be edited by hand.

How it goes on

Logic errors are found by watching the code run, which is what the next three lessons are for: breakpoints and stepping, the Immediate window with Debug.Print, and the Locals and Watch windows. Lessons five to eight take on run-time errors โ€” On Error GoTo handlers, the narrow cases where On Error Resume Next is legitimate, clean-up that restores your settings, and logging so a failure at 03:00 leaves a trail.

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.

Three kinds of error, three ways to find themCompile errorbefore it runsDebug > Compilecost: minutesRun-time errorwhile it runsnumber + yellow linecost: an hourLogic errornever announcedF8, Debug.Printcost: a wrong reportFrom left to right: harder to notice, more expensive when missed.
The further right, the quieter the error. Compile and run-time errors announce themselves; a logic error ends up in the report.

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:

The Error Demo sheet. How the dates look depends on your regional settings and the column format.
RowDate (A)Customer (B)Amount (C)Stored asCounted by the macro as
201 Jan 2025Customer 11200.5NumberReal number
302 Jan 2025Customer 2940NumberReal number
403 Jan 2025Customer 31050.75TextNumber as text
504 Jan 2025Customer 4380.25NumberReal number
605 Jan 2025Customer 5(empty)EmptyBlank
706 Jan 2025Customer 6610NumberReal number
807 Jan 2025Customer 7pendingTextOther text
908 Jan 2025Customer 81499.9TextNumber 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.

Column C of Error Demo: what Excel really stored012345Real numbers4Numbers as text2Other text1Blank cells1
What the macro counts in C2:C9. Half of the column is not what it looks like.

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.

The same eight cells, three answers. Only the first is a bug; which of the other two is right depends on whether the text cells are real sales.
CalculationExcel formulaVBAResult
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 ColumnHealthCheck782.69
Average after converting the text numbers=AVERAGE(C2:C9) after the fixSame code, run again946.90

Three averages from the same eight cells03006009001,200Sum / CountA (the trap)447.25Real numbers only782.69Text numbers converted946.90
The trap reports 447.25, which is 43% below the average of the real numbers and more than half below the average of all six amounts.

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

  1. Switch on Require Variable Declaration. In the editor (Alt+F11) choose Tools โ†’ Options โ†’ Editor and tick Require Variable Declaration. New modules will start with Option Explicit. Add the line by hand to every existing module.
  2. 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.
  3. 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.
  4. 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 with F5; it pauses there.
  5. Step through. Press F8 to run one line at a time. Shift+F8 steps over a call without going into it, Ctrl+Shift+F8 runs to the end of the current procedure, and F5 continues to the next breakpoint.
  6. Print what the code sees. Open the Immediate window with Ctrl+G and add a Debug.Print line inside the loop, as shown below. Type ?total and press Enter while paused to see a value on demand.
  7. Watch all variables at once. View โ†’ Locals Window lists every variable of the paused procedure with its value and type, updated after each step.
  8. Stop a runaway macro. Ctrl+Break (on some laptops Esc or Fn plus a key) interrupts a running macro and offers Debug.
  9. 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.

Errors and Debugging in Excel VBA course: finding compile, run-time and logic errors in macros
The Errors & Debugging course: find out what your macro is really doing, and fail gracefully when something goes wrong.

Common mistakes and how to spot them

  • No Option Explicit. A typo like totl = totl + cell.Value silently creates a new, empty variable, and the report shows 0. Spot it: the first line of the module is not Option Explicit.
  • Dividing by a count of the wrong thing. CountA counts text, Count counts 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 with ws.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 an If in front.
  • On Error Resume Next at 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 by On Error GoTo 0.
  • Debugging by MsgBox. A message box inside a 500-row loop means 500 clicks. Spot it: if you find yourself pressing Enter repeatedly, replace it with Debug.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

Shortcuts are for the VBA editor on Windows.
ItemKey or codeWhat it does
Compile projectDebug โ†’ Compile VBAProjectFinds compile errors in every module
Run / continueF5Runs the procedure or continues after a pause
Step into / over / outF8 / Shift+F8 / Ctrl+Shift+F8One line at a time, skipping or leaving called procedures
Toggle breakpointF9Pauses the macro on that line
Immediate windowCtrl+GShows Debug.Print output; ?expr evaluates
InterruptCtrl+BreakStops a running macro
Stored typeVarType(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 9Subscript out of rangeName or index not in the collection
Error 11 / 13Division by zero / Type mismatchGuard the divisor / check the type
Error 91Object variable not setAn 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, then Option Explicit in 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.

  1. Breakpoints and Stepping
  2. The Immediate Window and Debug.Print
  3. The Locals and Watch Windows
  4. On Error GoTo: Catching Failures
  5. On Error Resume Next, Used Carefully
  6. Cleanup Patterns That Never Leak
  7. Raising and Logging Your Own Errors

Buy course โ€” $9.90 See the full course

Knowledge check

A report divides Application.Sum of a column by CountA of the same column. Two cells in it hold numbers that are stored as text. What happens?

Continues in this course
  • 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

Buy the course to unlock the remaining 7 lessons, the exam and the certificate.

Buy course โ€” $9.90