Part III: More-Advanced Access Techniques
826
Note
A VBA label is nothing more than an identifier (such as HandleError) followed by a colon. A word by itself
on a line in a VBA procedure is interpreted as the name of a procedure, variable, or VBA keyword, and VBA
tries to evaluate it. When followed by a colon, the VBA interpreter understands that the word is actually a
label and should not be executed or evaluated.
The On Error statement is a switch that disables the default VBA error handling. This statement
switches the VBA engine away from its built-in error handling and redirects error handling to your
code. After you set the error trap with the On Error statement, you suppress the appearance of
the default Access error dialog boxes.
After an error occurs, the VBA engine’s normal operation is suspended. Normal execution is
directed to the error handler, and further error trapping is inhibited. If an error occurs in your
error handler, VBA responds with its default behavior. Some resources (discussed in the next sec-
tion) determine which error occurred and exactly where the error occurred. You also have several
options as to where you want program flow to commence after the error handler has done its job.
Note
There is nothing special about the labels used in the error-handling statements. HandleError and ExitHere
are just words; they convey no special meaning to Access or the VBA language engine. I use HandleError
and ExitHere throughout this book simply because they’re easily understood, but choose any label you want.
In fact, you can use exactly the same labels in every VBA procedure. This fact makes it easier to copy and paste
the error-handling template from one procedure to another in your Access application.
Trapping Errors with VBA
Several situations can cause a great deal of frustration for your application users:
l (^) A program that has been operating without a hint of trouble suddenly crashes, pop-
ping up a dialog box containing a contradictory or confusing error message.
l (^) A program behaves inconsistently. In one situation, the program operates in a predict-
able fashion, reliably churning out reports and displaying the results of calculations.
Under other conditions, though, the program, operating on seemingly identical data,
behaves erratically, stopping execution, or, perhaps, displaying the data in unexpected
ways.
l A program appears to be functioning properly but is in fact corrupting (unexpectedly
changing the value of) data. The program silently makes changes to the data or reports
erroneous values without indicating that an error exists. For example, in a program that
calculates currency exchange rates, the user of this program may believe the program is
correctly calculating the monetary exchange values while, in fact, the program is actually
reporting incorrect results.