Locked lesson.
About this lesson
How to set up an error trap in VBA to handle errors.
Quick reference
Trapping and Handling errors
Trapping and handling errors in your code
When to use
When you need to guard against (or trigger) errors in your code
Instructions
All errors have a numeric identifier
- When code is running, the error number is 0 if there are no errors.
- As soon as an error is triggered, it has an error code, an error number, and a description
Trapping Errors
- Find the line of code that you suspect could encounter an error at run time
- Insert a line immediately above with the code "On Error Resume Next" (this will suppress the error message)
- Use an If statement to test if the Err.Number <> 0
- If the test is true, an error was encountered. If not, no errors were triggered
Reset Error Handling
- After the test is run, resume normal error handling with the On Error GoTo 0 command
- This command clears any error number that has been logged
Syntax for trapping errors
On Error Resume Next
‘Comments
<Code which you suspect contains the error>
If Err.Number <> 0 Then
MsgBox Err.Number & “: “ & Err.Description
Exit Sub
End If
On Error GoTo 0
Hints & tips
- Be sure to add On Error GoTo 0 command after the If/Then test of the error number as this line of code clears the error codes
Lesson notes are only available for subscribers.