Today's Goals
- Understand why error handling matters
- Master the On Error statement
- Write your own error handlers
Key Concepts
1. The On Error Statement
vba' Jump to a label when an error occurs
On Error GoTo LabelName
' Ignore the error and keep going
On Error Resume Next
' Turn error trapping back on
On Error GoTo 0Three forms, three jobs: On Error GoTo LabelName is the safety net for the main flow, On Error Resume Next skips over a single, expected risk, and On Error GoTo 0 restores default error reporting. The recommended pattern is "GoTo as the net, plus narrowly targeted Resume Next exemptions".
2. The Error Handling Structure
vbaSub Example()
On Error GoTo ErrorHandler
' Code that may fail
Exit Sub
ErrorHandler:
' Handle the error here
MsgBox "Error: " & Err.Description
End SubTwo details matter. There must be an Exit Sub before the handler — otherwise normal execution "falls into" the error-handling section — and once you are done handling, clear the error with Err.Clear.
3. The Err Object
Err holds the most recent run-time error: Err.Number is the error code (0 means no error), Err.Description is the English description, and Err.Clear resets it. The standard test is If Err.Number <> 0 Then.
Today's Code
vbaSub ErrorHandlerExample()
On Error GoTo ErrorHandler
Dim ws As Worksheet
' Operation that may fail
Set ws = Worksheets("NoSuchSheet")
ws.Range("A1").Value = "test"
Exit Sub
ErrorHandler:
MsgBox "An error occurred!" & vbCrLf & _
"Number: " & Err.Number & vbCrLf & _
"Description: " & Err.Description, vbCritical, "Error Info"
End Sub
Sub ResumeNextExample()
On Error Resume Next
' Keep going even if a line fails
Worksheets("Sheet1").Range("A1").Value = "test"
Worksheets("NoSuchSheet").Range("A1").Value = "this line will not raise an error"
On Error GoTo 0 ' Restore error trapping
MsgBox "Code finished", vbInformation
End SubReal-World Scenario
You export results to a CSV, but the target folder may not exist — let error handling catch that instead of crashing:
vbaSub ExportData()
On Error GoTo ErrorHandler
Open "D:\Reports\Summary.csv" For Output As #1
Print #1, "Date,Sales"
Close #1
MsgBox "Export succeeded", vbInformation
Exit Sub
ErrorHandler:
Close #1 ' Prevent a leaked file handle
MsgBox "Export failed: " & Err.Description, vbCritical
End SubIf the folder is missing, Open raises Run-time error '76': Path not found and control jumps to ErrorHandler instead of crashing. In real projects the MsgBox is usually replaced with logging.
Exercises
- Build a program with complete error handling
- Handle the file-not-found error
- Log errors to a file
Exercise Solutions
- Use the
On Error GoTo ErrorHandlerstructure and handle the error at the ErrorHandler label. - Before opening a file, check whether it exists with the
Dirfunction, or catch the failure withOn Error Resume Next. - Write the error information to a text file or a cell using the
Openstatement andPrint #.
Common Errors and Troubleshooting
Run-time error '9': Subscript out of range— you referenced a sheet that does not exist. Probe for it with Resume Next plusErr.Number.Run-time error '13': Type mismatch—InputBoxreturns an empty string when the user cancels, and it goes straight into a calculation; check for "" first.Run-time error '91': Object variable or With block variable not set— theSetwas swallowed by Resume Next, so the object is still Nothing.- Normal execution falls into the error handler — you forgot
Exit Sub, so the main flow runs on into the code under the label. - Forgetting
On Error GoTo 0after Resume Next — error trapping stays off, and later errors are silently skipped.
Extension Exercises
- Rework the real-world scenario: use
Dirto check whether the output file already exists; if it does,Killit first and handle that failure too. - Write a
SafeOpenWorkbookfunction that returns Nothing on failure, and have callers test the result withIs Nothing.
由在线工具箱(www.vba.net)整理制作