Error Handling
- 02:06
How to write a simple error handling procedure in Excel VBA.
Downloads
No associated resources to download.
Transcript
Errors may occur in our VBA procedures, syntax errors which must be corrected before the code can be executed and runtime errors which occur whilst the procedure is running.
Runtime errors have the potential to cause huge embarrassment, especially if we are demonstrating our Excel VBA project to a colleague or client error handling procedure can avoid such embarrassment by stopping the code, continuing to run and taking a specified action.
Let's walk through the on error statement and the required syntax to construct a simple error handling procedure before the sub coding instructions, we write on error go-to and our chosen error handler name.
After the sub coding instructions, we state exit sub and then we state our error handler name followed by a colon.
The next line of code provides the instructions to follow if a runtime error is encountered.
In this example, we have the required syntax of on error go-to and the name of our error handler.
My error trap.
The sub instructions take an active cell and offset this by one cell to the left.
This is absolutely fine unless the active cell is in column A of our spreadsheet.
The My Error trap instructions use a VBA message box function to display a window with a text error found and the sub procedure ends.
We should note Go To statements transfer the code execution to a new instruction.
Go To is not terribly good coding style and only really useful for error handling procedures.