Question
How is 'On Error GoTo Label' implemented syntactically in a VBA procedure?
Asked by: USER4334
74 Viewed
74 Answers
Responsive Ad After Question
Answer (74)
To implement 'On Error GoTo Label', you place the statement 'On Error GoTo YourLabelName' at the beginning of the procedure where you want to handle errors. Then, at the end of the procedure, you define the label (e.g., 'YourLabelName:') followed by the error-handling code. Crucially, an 'Exit Sub' or 'Exit Function' statement must be placed immediately before the label to prevent the code from executing the error handler inadvertently after successful execution of the main code. Example:
```vba
Sub MyProcedure()
On Error GoTo ErrorHandler
' Main code block
Dim x As Integer
x = 10 / 0 ' Example: Division by zero error
MsgBox "This line will not execute if an error occurs above."
Exit Sub ' Essential to exit before error handler
ErrorHandler:
MsgBox "An error occurred: " & Err.Description & " (Error #" & Err.Number & ")", vbCritical
' Optional cleanup code
End Sub
```