Microsoft Office Tutorials and References
In Depth Information
Trapping Runtime Errors
The location of the error is highlighted in blue. The message box in
Figure 6-1, for example, shows that the compiler was expecting an End
Sub statement after the blue highlight. You can click the Help button for
more information about the error, although in this example, the fix is
pretty easy. Every sub procedure needs an End Sub statement, and one
of the procedures in this module has no End Sub statement. Click OK to
close the error message box; then type the missing End Sub statement
after the blue highlight.
When you can choose Debug Compile name without seeing any error
messages, you know that all your code is compiled and free of compiler errors.
The Compile command is disabled (dimmed) because no uncompiled code is
left to compile. Any remaining errors are runtime or logical errors.
Trapping Runtime Errors
Some VBA errors may be caused by events in the environment rather than in
the code. Here are a couple of examples:
Your code performs some operation on data in an open form. If the form
isn’t open when the code executes, code execution stops, a runtime
error occurs, and an error message pops up onscreen.
An expression performs division using data from a table, and the divisor
ends up being 0 (zero). Because dividing a number by 0 doesn’t make
sense, code execution stops, a runtime error occurs, and an error
message appears.
If people who know nothing about Access use the database that you create,
the error messages that pop up onscreen aren’t likely to help those users
much. What you want to do is anticipate what kinds of errors may occur,
trap them (that is, tell Access to let you know when they happen), and fix
them when they occur. To do this, you add an error handler to your code.
An error handler is a chunk of code within the procedure that intercepts the
error and fixes the problem without stopping code execution or displaying
an error message.
Book VIII
Chapter 6
Creating an error handler
To create an error handler, the first order of business is adding an On
Error statement to your code — preferably just after the Sub or Function
statement that marks the beginning of the procedure. You have three ways
to create an On Error statement:
On Error GoTo label When an error occurs as a statement runs, :
code execution jumps to the section of code identified by label within
the same procedure.
 
Search JabSto ::




Custom Search