Error Handling In VBA
This page discussese error hanlding techniques in VBA.
The term error handling refers to the practice of detecting errors that may arise when
code exectues and how to handle such errors. Errors fall into three broad categories. Compiler
errors, which arise when you compile the code. An undeclared variable is a typical error situation. All
compiler errors must be fixed before the code can run. Logic error arise due to faulty programming. In these
cases, the code often runs without error, but the result are not what is expected. Fixing these errors requires
a careful analysis of the code and its intended purpose. The third type of error occurs when some resource or
value used in the code is invalid or unavailable. For example, a run time error will occur if you attempt to
access a workshet name "Sheet1" and no such worksheet exists. On this page, we will examine only the last type
of error, the run time error. We will not address compiler errors or logic errors.
As a general good programming practice, your code should test for the existence and validity for all the resourses it
will need once the real code begins. For example, ensure that any required worksheets are present. If your code
detects conditions during the first part of a procedure, you can gracely exit out of the procedure and notify the
user of the error condition. This is preferable to letting the code run part way through before an error condition is
detected. If the code makes changes to a worksheet and midway through finds an erroreous condition, your code will have
to undo all changes, restoring values back to their original values or you will leave the worksheet in an unknown and
indeterminate state. Regardless of the environment in which the code is run, you want to avoid an error at all costs. Nothing
will undermine your credibility with a client more than an untrapped error message that allows the user only to terminate execution
and leave the work undone.
Runtime error handling is managed by the On Error statement.
Narrative goes here.
|
This page last updated: 28-Oct-2008. |