Microsoft Office Tutorials and References
In Depth Information
When you pass arguments to a procedure, the data that is passed as the argument must match
the argument’s data type. For example, if you call Process in the preceding example and pass a
string variable for the first argument, you get an error: ByRef argument type mismatch .
Arguments are relevant to both Sub procedures and Function procedures. In fact,
arguments are more often used in Function procedures. In Chapter 10, where I focus
on Function procedures, I provide additional examples of using arguments with your
routines, including how to handle optional arguments.
When a VBA procedure is running, errors can (and probably will) occur. These include either
syntax errors (which you must correct before you can execute a procedure) or runtime errors (which
occur while the procedure is running). This section deals with runtime errors.
for error-handling procedures to work, the Break on All Errors setting must be turned
off. In the VBE, choose Tools➜Options and click the General tab in the Options dialog
box. If Break on All Errors is selected, VBA ignores your error-handling code. You’ll
usually want to use the Break on Unhandled Errors option.
Normally, a runtime error causes VBA to stop, and the user sees a dialog box that displays the
error number and a description of the error. A good application doesn’t make the user deal with
these messages. Rather, it incorporates error-handling code to trap errors and take appropriate
actions. At the very least, your error-handling code can display a more meaningful error message
than the one VBA pops up.
Appendix C lists all the VBA error codes and descriptions.
You can use the On Error statement to specify what happens when an error occurs. Basically,
you have two choices:
h Ignore the error and let VBA continue. Your code can later examine the Err object to
determine what the error was and then take action, if necessary.
h Jump to a special error-handling section of your code to take action. This section is
placed at the end of the procedure and is also marked by a label.