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.
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.
Errors can be handled in VBA procedures using the On Error statement, as I show you next.
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:
On Error GoTo HandleError
'normal code for the procedure goes hereExit Sub
'code for handling the error goes here Exit 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 ...