18-Error Handler in VBA For Excel

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Error Handler in VBA for Excel

VBA Lesson 18: VBA for Excel to Manage Errors

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.

Here is the basic way to handle errors.

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"

http://www.excel-vba.com/vba-code-2-2-error.htm (1 of 3) [9/19/2009 4:32:42 PM]


Error Handler in VBA for Excel

Example 1:

Sub proTestErrorHandler()

On Error GoTo addJump


Workbooks.Open "xxxxxx"
Exit Sub

addJump:

MsgBox "An error has occurred, call Peter at 1 613-749-4695"

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 .

Discover More Tips, Ideas and Examples on this Topic


In the complete lesson of the
Downloadable Tutorial on Excel Macros

Quick links to the three sections of this website

Section 1: Excel Macros Programming: 10 lessons


Section 2: Excel VBA Vocabulary: 13 lessons
Section 3: Excel VBA Userforms: 10 lessons

http://www.excel-vba.com/vba-code-2-2-error.htm (2 of 3) [9/19/2009 4:32:42 PM]


Error Handler in VBA for Excel

http://www.excel-vba.com/vba-code-2-2-error.htm (3 of 3) [9/19/2009 4:32:42 PM]

You might also like