Subscriber only lesson.
Sign up to this course to view this lesson.
About this lesson
Setting up an error handling section for your macro.
Download this lesson’s exercise file.Building error handlers.xlsm
Building error handlers
Buidling proper frameworks to handle errors
When to use
To create a VBA error handler that can be used anytime an error is triggered in your code
Setting a Label
- Instead of using the On Error Resume Next command to begin a test, use On Error GoTo <Label>
- A label allows us to jump to that section of code whenever it is referenced
- Every time an error is triggered, the code will jump to the error handler label and execute the code in the error handler
- To create a label, type your label name followed by a colon (:)
Running the Error Handler
- As the error handler will be near the bottom of the routine, you will usually want to exit the subroutine before you hit that point. (Failure to do so will run your error handling code even if an error is not present.)
- To exit the subroutine before your error handler label, type Exit Sub
- After the steps of the error handler are performed, use the Resume command to return to the line of code immediately after the line where the error occurred
Syntax format for an error handler
Sub MacroName ()
Dim Variable1 As VariableType
On Error GoTo LabelName
<Code that may contain the error>
Select Case Err.Number
Case Is = <Error Number>
Hints & tips
- After you create your label by adding the colon to your label name, the Visual Basic Editor will automatically align this line to the far left
Lesson notes are only available for subscribers.