VBA Error Handling with On Error and Err: Reliable Patterns
VBA Error Handling with On Error and Err: Reliable Patterns is a practical guide to solving a repeatable Office automation problem. A macro opens a report workbook; if the file is missing or a required worksheet is absent it must log the error, release resources and explain the failure. We begin by defining the source and the desired output, walk through the technique in manageable stages, and finish with tests, failure cases and operational handover. The goal is not simply to memorize a function name: the reader should be able to measure the result, explain discrepancies and make later changes without losing control of the workflow.
Problem and learning objective
A macro opens a report workbook; if the file is missing or a required worksheet is absent it must log the error, release resources and explain the failure.
Before touching a production workbook or database, create a small, recoverable example. A few normal rows, one missing value, one duplicate and at least one boundary case are often enough to expose mistakes. Write the expected answer before running the tool rather than treating a visually attractive grid or a success message as proof. In business reporting, data quality is part of the solution itself, not an optional task performed after coding.
Separate the problem into three layers: incoming data, the transformation or calculation rule, and an output that someone can use. This distinction helps determine whether a failure came from a source file, an incorrect type assumption, or the reporting layer. At each stage record column names, row counts, date limits and stable identifiers. A small audit summary makes it far easier to explain why next month’s report differs from this month’s.
Prerequisites and assumptions
In VBA, enable Option Explicit and minimize implicit reliance on ActiveWorkbook or ActiveSheet. Resolve each target workbook and worksheet explicitly so a user click does not redirect a macro toward another file. For multi-file jobs, close every source after reading it and restore application settings such as ScreenUpdating on both success and failure paths. These are operational requirements, not optional decorations for production code.
Tutorial datasets are deliberately compact, so avoid copying examples directly into live processes without reviewing assumptions. Operational data includes locked files, renamed columns, numeric values stored as text and identifiers that unexpectedly repeat. Decide ahead of time whether each case should be rejected, stop the whole job or produce an actionable warning. Each policy can be appropriate, but a silent and unexamined outcome rarely is.
Consider maintenance after the first successful run. A solution may fail later because someone renames a worksheet, adds a source column or upgrades Office. State the essential assumptions at the top of the exercise and near the code that relies on them. When an assumption is violated, a clear error and controlled stop are safer than silently exporting an incomplete report. Good documentation often outlasts clever code tricks.
Step-by-step implementation
A useful automation is repeatable. Given the same source and settings, another run should produce an explainable result instead of depending on which cell was selected or which file happened to be open. Keep constants in one place, document the sequence and make dependencies on the current date or local file path explicit. The less hidden state a procedure uses, the easier it is to debug and hand over to a colleague.
Locate the risky action and required cleanup
At this stage: Identify objects that may be partially initialized, such as an opened Workbook, and plan how each will be closed after failure. Apply this to a small test case and compare the outcome with its input before moving to the next step.
Test “Locate the risky action and required cleanup” with one normal input and one boundary case. Record the column names, data types and observed result together. If this checkpoint fails, correct its assumption rather than suppressing the error.
Install a scoped On Error GoTo handler
At this stage: Install On Error GoTo Failed before Workbooks.Open so a missing file follows a controlled diagnostic route. Apply this to a small test case and compare the outcome with its input before moving to the next step.
Test “Install a scoped On Error GoTo handler” with one normal input and one boundary case. Record the column names, data types and observed result together. If this checkpoint fails, correct its assumption rather than suppressing the error.
Route the success path to cleanup
At this stage: Route success through CleanExit as well, so one cleanup path handles both ordinary completion and recovery. Apply this to a small test case and compare the outcome with its input before moving to the next step.
Test “Route the success path to cleanup” with one normal input and one boundary case. Record the column names, data types and observed result together. If this checkpoint fails, correct its assumption rather than suppressing the error.
Capture Err.Number and Description immediately
At this stage: Copy Err.Number and Err.Description into variables before Resume or other cleanup statements can change them. Apply this to a small test case and compare the outcome with its input before moving to the next step.
Test “Capture Err.Number and Description immediately” with one normal input and one boundary case. Record the column names, data types and observed result together. If this checkpoint fails, correct its assumption rather than suppressing the error.
Release Workbook and Recordset resources
At this stage: Use Resume Next narrowly for cleanup operations, then restore normal error handling instead of suppressing the main procedure. Apply this to a small test case and compare the outcome with its input before moving to the next step.
Test “Release Workbook and Recordset resources” with one normal input and one boundary case. Record the column names, data types and observed result together. If this checkpoint fails, correct its assumption rather than suppressing the error.
Exercise the failure branch deliberately
At this stage: Temporarily rename report.xlsx and check that an informative error appears and no unrelated workbook remains open. Apply this to a small test case and compare the outcome with its input before moving to the next step.
Test “Exercise the failure branch deliberately” with one normal input and one boundary case. Record the column names, data types and observed result together. If this checkpoint fails, correct its assumption rather than suppressing the error.
Working example and code review
The following example demonstrates the structure of VBA error handling in a form that can be adapted to a sample workbook or database. Replace the sample table and file names with those in your test environment. Put VBA in a standard module inside a macro-enabled workbook, M code in Power Query Advanced Editor, and spreadsheet expressions in an appropriate worksheet cell.
Option Explicit
Public Sub ReadReportSafely()
Dim wb As Workbook
Dim errorNumber As Long, errorText As String
On Error GoTo Failed
Set wb = Workbooks.Open(ThisWorkbook.Path & Application.PathSeparator & "report.xlsx", ReadOnly:=True)
Debug.Print wb.Worksheets(1).Range("A1").Value2
CleanExit:
On Error Resume Next
If Not wb Is Nothing Then wb.Close SaveChanges:=False
On Error GoTo 0
If errorNumber <> 0 Then MsgBox errorText, vbExclamation
Exit Sub
Failed:
errorNumber = Err.Number
errorText = "Error " & errorNumber & ": " & Err.Description
Resume CleanExit
End Sub
After running the example, reconcile source rows with the output. A macro opens a report workbook; if the file is missing or a required worksheet is absent it must log the error, release resources and explain the failure. When multiple operations are involved, validate each one separately: the success of a later step does not prove an earlier transformation was correct. For real customer or finance records, keep an auditable error trail and avoid printing confidential data into broad-access logs or the VBA Immediate Window.
Validation and edge-case tests
Correctness comes before speed. A fast but inaccurate financial summary is worse than a slower report whose totals can be independently reconciled. Compare row counts and control totals with the source and manually inspect some included and excluded records. Repeat those same checks whenever a formula, query or table structure changes. This lightweight regression test is often more valuable than adding another layer of clever automation.
Finish every exercise with a measurable acceptance criterion, not merely a screenshot. The number of processed files should match the eligible input count; a control total should remain consistent; or output identifiers should match the reference table. Explain the result to someone who did not write the automation. If that explanation is difficult, an important assumption or business rule probably remains implicit and deserves another review.
Store runnable examples in a standard module inside a macro-capable workbook such as xlsm. Excel-specific methods do not necessarily behave the same way in Access or Word. Begin testing with a backup and synthetic inputs. If an example requires an external object library, document the reference or use late binding with an explicit compatibility note so a Missing Reference does not surprise users.
Common pitfalls
| Symptom or risk | Check and correction |
|---|---|
| An unexpected input structure or result at checkpoint 1; confirm field names, types and output cardinality. | Before repeating the full workflow, inspect the test input, record the relevant values and rerun stage 1 independently. Suppressing an error before finding the cause risks an incomplete result. |
| An unexpected input structure or result at checkpoint 2; confirm field names, types and output cardinality. | Before repeating the full workflow, inspect the test input, record the relevant values and rerun stage 2 independently. Suppressing an error before finding the cause risks an incomplete result. |
| A source field has the wrong data type for the operation. | Inspect the column type and a sample value first. |
| New records changed totals or result shape unexpectedly. | Recompute row counts and reconciliation totals. |
Keep a testing workflow separate from the production workflow. Consistent names, recoverable backups and a simple change log prevent many avoidable failures. For finance or personnel data, do not publish real personal records as sample content. If a process produces a downloadable or transferable document, inspect its filename, scope, format and destination before delivery. Automation reduces repetitive effort but does not eliminate responsibility for the results.
Best practices and maintainability
Distinguish runtime exceptions from invalid business data. A negative amount, blank account key or wrongly selected file might not raise an exception yet can still corrupt a report. Validate inputs before the risky action, then wrap that action in traceable error handling. A useful log identifies the file or row, the error number and whether cleanup succeeded. Do not use a blanket error suppression statement as a substitute for validation.
Consider maintenance after the first successful run. A solution may fail later because someone renames a worksheet, adds a source column or upgrades Office. State the essential assumptions at the top of the exercise and near the code that relies on them. When an assumption is violated, a clear error and controlled stop are safer than silently exporting an incomplete report. Good documentation often outlasts clever code tricks.
Correctness comes before speed. A fast but inaccurate financial summary is worse than a slower report whose totals can be independently reconciled. Compare row counts and control totals with the source and manually inspect some included and excluded records. Repeat those same checks whenever a formula, query or table structure changes. This lightweight regression test is often more valuable than adding another layer of clever automation.
Practice exercise
Create a compact practice version of “VBA Error Handling with On Error and Err: Reliable Patterns”. Add three new inputs: one valid row, one duplicate and one row with a missing value. Write down the expected outcome for each before running the workflow. Compare actual and predicted results side by side, then deliberately rename a column or change a file path to observe failure handling. Finally document how to restore a correct run without deleting useful diagnostic information.
A useful automation is repeatable. Given the same source and settings, another run should produce an explainable result instead of depending on which cell was selected or which file happened to be open. Keep constants in one place, document the sequence and make dependencies on the current date or local file path explicit. The less hidden state a procedure uses, the easier it is to debug and hand over to a colleague.
Finish every exercise with a measurable acceptance criterion, not merely a screenshot. The number of processed files should match the eligible input count; a control total should remain consistent; or output identifiers should match the reference table. Explain the result to someone who did not write the automation. If that explanation is difficult, an important assumption or business rule probably remains implicit and deserves another review.
Related topics
Use the related lessons below to develop a connected learning path. Planned links can be activated once their destination articles are published.
- VBA Data Types
- Combine Multiple Excel Files from a Folder with Power Query
- Clean and Reshape Excel Data with Power Query Unpivot and Refresh
- Excel XLOOKUP Tutorial: Exact Matches and Missing Values
Frequently asked questions
VBA error handling: What problem does this technique solve?
This method is useful when its input and intended output can be stated precisely. A macro opens a report workbook; if the file is missing or a required worksheet is absent it must log the error, release resources and explain the failure. Start by checking “Locate the risky action and required cleanup”, then compare a valid record with an invalid or missing-data case. A mismatch does not automatically require rewriting the whole solution; rerun the checkpoint where the result first diverges. This disciplined approach is easier to teach, audit and maintain than a sequence of unexplained clicks.
What should be checked before using it?
This method is useful when its input and intended output can be stated precisely. A macro opens a report workbook; if the file is missing or a required worksheet is absent it must log the error, release resources and explain the failure. Start by checking “Install a scoped On Error GoTo handler”, then compare a valid record with an invalid or missing-data case. A mismatch does not automatically require rewriting the whole solution; rerun the checkpoint where the result first diverges. This disciplined approach is easier to teach, audit and maintain than a sequence of unexplained clicks.
What happens when source data is incomplete?
This method is useful when its input and intended output can be stated precisely. A macro opens a report workbook; if the file is missing or a required worksheet is absent it must log the error, release resources and explain the failure. Start by checking “Route the success path to cleanup”, then compare a valid record with an invalid or missing-data case. A mismatch does not automatically require rewriting the whole solution; rerun the checkpoint where the result first diverges. This disciplined approach is easier to teach, audit and maintain than a sequence of unexplained clicks.
How can the result be verified?
This method is useful when its input and intended output can be stated precisely. A macro opens a report workbook; if the file is missing or a required worksheet is absent it must log the error, release resources and explain the failure. Start by checking “Capture Err.Number and Description immediately”, then compare a valid record with an invalid or missing-data case. A mismatch does not automatically require rewriting the whole solution; rerun the checkpoint where the result first diverges. This disciplined approach is easier to teach, audit and maintain than a sequence of unexplained clicks.
Is this suitable for production reporting?
This method is useful when its input and intended output can be stated precisely. A macro opens a report workbook; if the file is missing or a required worksheet is absent it must log the error, release resources and explain the failure. Start by checking “Release Workbook and Recordset resources”, then compare a valid record with an invalid or missing-data case. A mismatch does not automatically require rewriting the whole solution; rerun the checkpoint where the result first diverges. This disciplined approach is easier to teach, audit and maintain than a sequence of unexplained clicks.
Conclusion
VBA error handling becomes genuinely useful when its result is repeatable and independently checkable. A macro opens a report workbook; if the file is missing or a required worksheet is absent it must log the error, release resources and explain the failure. By working in small stages, testing edge cases and recording assumptions, a short example can become a reliable workflow. Before processing live records, repeat the checks on a backup and confirm compatibility with the relevant Office version and data model.
Read More
Conditional and Logical Statements in VBA | Program Flow Control and Interactive Practice
Your First VBA Programme | Put Your Knowledge into Practice
Immediate Window | Understanding the VBA Immediate Window
VBA Built-in Functions | Complete List of Functions in Visual Basic
VBA Procedures | Definition, Types & Usage in Visual Basic
Constants in VBA | Types, Scope, and How to Use Them Effectively
Variable Scope in VBA | How to Access Variables across Different Parts of a Project