VBA - Error Handling

Programs often depend on external data and user interaction - which often can lead to undesired behavior. For example missing data, data in the wrong format or users entering something special. If this breaks the program we need a way to control what happens and how the user is informed of an issue.

For the following examples we will use a divide by zero error to trigger the error handling code.

Here is an example of the most basic error handling, "Resume Next":

Resume Next will simply ignore errors and move on to the next bit of code. This is a very poor way to handle errors as the final output is unpredictable. In the example above we output the error number that have been generated. This output 11.

In the above example we have used "On Error GoTo ..." to change the flow of the program to move to the label. This is a much improved method of handling errors as the behavior is now predictable and controlled.

This example above includes the statement "On Error GoTo 0" returns the code into the unhanded state.

Related Sections

Python - Learn the python from the basics up. This fast track example code course will get you creating powerful python programs in no time.

Must Read Articles

VBA and Microsoft Excel - Getting the most out of excel with VBA programming
VBA and Microsoft Word - Getting the most out of word with VBA programming
Application Object - Using the applications features in your code.
Installing VBA and First Program - What do you need to start using visual basic application VBA.