Errors
VBA Error Handling Flow Summary
Section titled “VBA Error Handling Flow Summary”| Step | Description |
|---|---|
| On Error GoTo Label | Sets the error handler label; redirects to this label if a runtime error occurs. |
| Normal code execution | Runs code normally until an error occurs or procedure ends (via Exit Sub/Function). |
| Error occurs | Execution jumps immediately to the error handler label. |
| Error Handler block | Executes error handling code (e.g., logging, cleanup, user messages). |
| Resume statements | Control flow options after error handling: |
| - Resume | Re-execute the error-causing line (retry). |
| - Resume Next | Skip the error line; continue with the next statement. |
| - Resume | Jump to a specific label (often cleanup) before continuing or exiting. |
| Exit Sub/Function before handler | Prevents normal code from running into the error handler block accidentally. |
| Cleanup code (optional) | Frees resources or resets state before exiting or continuing. |
| End of procedure | When no error or after error handling with no resume, execution ends at End Sub/Function. |
modErrorHandler
Section titled “modErrorHandler”This module contains a general error handler.
Usage:
After declarations, add this
On Error GoTo Error_HandlerAdd the module code and then
Cleanup: Set openObject = Nothing Exit Function
Error_Handler: GeneralErrorHandler err, Me.Name, "ReplaceWithProcedureName" Resume CleanupEnd FunctionOr for a subroutine
Cleanup: Set openObject = Nothing Exit Sub
Error_Handler: GeneralErrorHandler err, Me.Name, "ReplaceWithProcedureName" Resume CleanupEnd SubCleanup with object
Cleanup: Set openObject = Nothing Exit SubCleanup without object
Cleanup: Exit SubFrom error
Error_Handler: GeneralErrorHandler err, Me.Name, "ReplaceWithProcedureName" Resume CleanupModule error
Error_Handler: GeneralErrorHandler err, MODULE_NAME, "ReplaceWithProcedureName" Resume CleanupNz Function Summary
Section titled “Nz Function Summary”| Argument | Description |
|---|---|
| variant (required) | The value to check for Null (can be a field, control, variable). |
| valueifnull (optional) | The value to return if variant is Null. Defaults to 0 for numbers, "" for strings (but specifying it explicitly is best). |
- Returns
variantif not Null. - Returns
valueifnullifvariantis Null. - Useful to avoid runtime errors when Null values might occur.
- Best practice: always specify
valueifnull, especially for strings, to ensure consistent results.