9.4. Basic Error Handling with a Twist

One of the problems with basic error handling is that when an error does occur, you have no easy way of knowing the exact line that caused the error. After all, your procedure may have dozens or hundreds of lines of code. When you see the error message, the execution of your code has already jumped to your error handler routine and displayed the message box; you may not be able to tell which line caused the problem. Many programmers rerun the code, using debug mode, to step through the code to try to find the offending line.

But there is a much easier way to find that error-producing line of code: Just add a Resume line after the Resume Exit_Procedure.

You're probably thinking: Why would I add an extra Resume right after another Resume Exit_Procedure? The extra Resume will never run! Well, you're right. It will never run under normal circumstances. But it will run if you ask it to. If your application encounters an error, you can override the next line that will run. In debug mode, you can just change the next line to be executed to your extra Resume. The Resume Exit_Procedure statement is skipped entirely. The following code is identical to the basic code shown previously, but with that one extra Resume.

Public Function MyFunction() On Error GoTo Error_Handler Dim varReturnVal As Variant 'your function code goes here Exit_Procedure: Exit Function 'or Exit Sub if this is a Sub Error_Handler: MsgBox "An error has occurred in this application. ...

Get Access 2003 VBA Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.