VBA Error Handling
Write robust VBA code with proper error trapping and handling techniques
Quick Reference
On Error Resume Next: Continue after errors (use cautiously)
On Error GoTo Label: Jump to error handler
On Error GoTo 0: Disable error handler
Err Object: Contains error information (Number, Description, Source)
Why Error Handling Matters
Without error handling, VBA code stops immediately when an error occurs, showing cryptic error messages to users. Proper error handling:
- Prevents code crashes and Excel freezes
- Provides user-friendly error messages
- Logs errors for debugging
- Allows graceful recovery or cleanup
- Makes code production-ready
❌ Without Error Handling
Code stops, shows "Run-time error 1004", leaves data in inconsistent state
✓ With Error Handling
Catches error, shows "File not found. Please check path", cleans up resources
On Error Resume Next
Continues execution on the next line after an error occurs. Use sparingly!
Basic Example:
Check for Errors After:
Warning: On Error Resume Next hides ALL errors, even unexpected ones. Always check Err.Number immediately after risky operations!
On Error GoTo (Recommended)
Jumps to a labeled error handler when an error occurs. This is the professional approach.
Basic Structure:
Complete Example with Cleanup:
Resume Statements:
The Err Object
VBA's built-in error object containing information about the last error.
Key Properties:
| Property | Description | Example |
|---|---|---|
| Number | Error code | 1004 |
| Description | Error message | "File not found" |
| Source | Source of error | "VBAProject" |
| HelpFile | Help file path | C:\Help.chm |
| HelpContext | Help topic ID | 1000 |
Key Methods:
Detailed Error Logging:
Common VBA Error Numbers
| Error # | Description | Common Cause |
|---|---|---|
| 5 | Invalid procedure call | Bad argument value |
| 6 | Overflow | Number too large for data type |
| 7 | Out of memory | Too many objects/variables |
| 9 | Subscript out of range | Array index invalid |
| 11 | Division by zero | Dividing by 0 |
| 13 | Type mismatch | Wrong data type |
| 53 | File not found | File path invalid |
| 91 | Object variable not set | Forgot Set keyword |
| 1004 | Application-defined error | Excel object model error |
Handling Specific Errors:
Raising Custom Errors
Use Err.Raise to create your own errors for validation and flow control.
Basic Custom Error:
Use vbObjectError + your number to avoid conflicts with VBA error numbers
Complete Example with Custom Errors:
Debugging Techniques
Debug.Print for Tracing:
View output in Immediate Window (Ctrl+G)
Breakpoints:
- Click left margin or press F9 to set breakpoint
- Code pauses at breakpoint - inspect variables
- F8 to step through line by line
- F5 to continue running