Professional Documents
Culture Documents
18-Error Handler in VBA For Excel
18-Error Handler in VBA For Excel
18-Error Handler in VBA For Excel
After you have written a macro and VBE has helped you correct most the errors...after you have tested you
macro there might still be error messages generated and you or the user will end up seeing this window:
This window is no problem if you or close colleagues are the only users of the workbook. But in other
rare cases where you distribute your workbooks to many users you will probably prefer to have a
more useful error message.
A VBA procedure usually runs from Sub to End Sub. In a VBA procedure that includes an error handler
it will run from Sub to Exit Sub but if there is an error happening during the execution it will jump to
a special address where the error handler resides.
So to add error handling capabilities to any of your VBA procedures you follow these steps:
1- Add an Exit Sub right before End Sub
2- Between these two lines add an address ending with a colon (addJump: for example)
3- Make room between the address line and End Sub to enter your code handling the error.
4- At the beginning of your code enter On Error GoTo addJump
5- As in the example below the error handler can be a message box giving your coordinates to the
user: MsgBox "An error has occurred, call Peter at 1 613-749-4695"
Example 1:
Sub proTestErrorHandler()
addJump:
End Sub
Copy/Paste the examples in a module of your own and run them. As the workbook xxxxxx can't be
found you will see a message box saying An error has occurred, call Peter at 1 613-749-4695 .