2.8. Error Handling

Now that you are familiar with various types of errors that can occur in your VBA code and how to debug them, it's time to look at how to write error-handling code in your procedures so that your application performs well for users.

2.8.1. Default Error Messages

You have all used applications that did not have very good error handling and found yourself getting booted out of the application without warning or faced with unfriendly messages like the ones you saw earlier in this chapter. You do not want such problems to happen when users interact with your application. Errors will always occur, but if you design error handlers correctly, at least they can be handled reasonably well.

2.8.2. Handling Errors with an On Error Statement

Errors can be handled in VBA procedures using the On Error statement, as I show you next.

2.8.2.1. On Error Statement

The On Error statement can be placed on your procedure to specify a section in the procedure to which the execution should jump when an error occurs. Here is an example:

Sub Test()
On Error GoTo HandleError
'normal code for the procedure goes hereExit Sub
HandleError:
'code for handling the error goes here
Exit Sub
End Sub

If you want to make sure your own error handler doesn't kick in when you're debugging your code, select Tools Options General and enable the Break On All Errors option. This will allow you to see ...

Get Beginning Access™ 2007 VBA now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.