Open In App

VBA Error Handling

Improve
Improve
Like Article
Like
Save
Share
Report

In a VBA code, there may be some errors like syntax errors, compilation errors, or runtime errors so we need to handle these errors. Suppose there is a code of 200 lines and the code has an error it’s very difficult to find an error in the code of 200 lines so it’s better to handle the error where we are expecting some error in our code. There are many error handling methods in VBA which we will discuss in this article but before that, we will discuss types of error.

What is VBA Error handling?

VBA Error handling is the process of Anticipating, detecting, and writing code to resolve the error that occurs when your application is running. The VBA Error handling process occurs when writing a code before any error occurs. Before moving to VBA Error handling first you need to know about the types of VBA Errors.

Types of VBA Errors

  • Syntax Error
  • Compilation Error
  • Run time Error
  • Logical Error

Syntax Error

Syntax errors are also called language errors, There are some particular syntaxes for writing any code, In VBA also user needs to follow a particular syntax, and if the user doesn’t write the syntax in the proper way it should be, then the user can face syntax errors. 

Note: Make sure the Auto syntax check should be activated in your VB editor (by default it is activated).

Auto syntax check is activated.

put a tick mark on the Auto syntax check

VBA will display an error message if the syntax is not correctly written.

Syntax-error-occurred

Error message 

Examples of Syntax Error

Example-of-syntax-error

syntax error 

Compilation Error

Compilation occurs over more than one line. In simple words, it can be understood as when something is missing that is needed for the code to run.

When there is a statement where there is an error in more than one line of its statement then VBA will display an error message. In the following example, a for loop is written without Next which is a compilation error.

Compilation-error-occurred

compilation error 

Runtime Error

As the name suggests Rum time errors are those which occur at the time of code running.

A code that is written perfectly but an error occurs at the time of execution. For example, if a file address is attached to the code which doesn’t exist or when a number is divided by zero a case runtime error occurs.

After correcting the error the user can click on the run button in the toolbar. (Shortcut key to run is F5). It will continue running the code from where it left off.

Note: If the user clicks on the send button from the dialog box, to come out of the code it will stop the code at the line at which is encountered All the lines of code before that would have been executed.

Runtime-error-occurred

Run time error.

Logical Error

Logical errors would not make your code stop but may lead to an output that is not desired. These errors are considered to be the most difficult type of error to troubleshoot.

The compiler can not highlight the logical errors but it will give a wrong output. The code will run without any error but the output will come wrong. In case of a large number of codes, it is difficult to identify the logical errors, to resolve this problem we need to press “F8” it will run the code one line at a time and we can identify the mistakes for which we are getting the wrong output. The following code is written to the difference between two numbers where we are getting the summation of two numbers.

Logical-error-found

summation of two  numbers instead of subtraction

Here, we can identify the logical error that instead of “-” we have written “+”

Expected Vs Unexpected Errors

  • Expected Errors: Where we are expecting to get an error, there we write our code to handle the error.
  • Unexpected Errors: Where we don’t need to write our code we have VBA error handling statements to handle the errors.

VBA Error Handling

VBA Error Handling refers to the process of anticipating, detecting, and resolving VBA Runtime Errors. The VBA Error Handling process occurs when writing code before any errors actually occur.

VBA On Error Statement

The VBA on error statements is used for error handling. This statement performs some action when an error occurs during run time. Without an Error statement, any run-time error that occurs is misfortunate. Execution stops abruptly with an error message. 

Most VBA error handling is done with the On Error Statement. The On Error statement instructs the VBA what to do if it encounters the error.

Below are On Error Statement:

  • On Error GoTo 0
  • On Error Resume Next
  • On Error GoTo Line

On Error

It is used to handle errors that occur during run time.

This Statement can be used in four different ways:

  1. On Error GoTo 0: The code stops at the line where the error occurred and displays the message.
  2. On Error Resume Next: No error message is displayed, the code will move to the next line.
  3. On Error GoTo [Label]: The code moves to a specific line or label.  No error message is displayed. This can be used for error handling.
  4. On Error GoTo -1:Clears the current error.

On Error GoTo 0

This is the default behavior of VBA that if an error occurred it stops the execution of the code and displays the error message. For continuation of the code it requires user intervention or the user needs to start the application again. In this process, no error handling is taking place.

For Example:

This statement will show an error message that a number or a variable is divided by zero.

Error-occurred-due-to-division-by-0

Division of numbers with zero is not possible. 

On Error Resume Next

 It tells VBA if it gets a run time error then don’t show the error message simply resume to the next statement. In simple language, it can be said that it tells VBA to ignore all the errors and continue.

Note: This is not considered to be good practice because if all the errors will be ignored then the result will be unpredictable. This can affect the code or application in multiple ways. 

Not-showing-error

 

On Error GoTo [label]

The above methods don’t truly allow us to handle the error but On Error, Goto [label] is the way with which the user can handle the error and it also specifies what you want to do with the code if an error occurs.

  • It is similar to try and catch functionality as in other programming languages such as c and c#. If it gets an error then it will go to the specific statement which we will mention in the “label” part.
Error-mentioned-in-label

On ErrorGoTo[label]

On Error Goto -1

This is used to clear the current error rather than setting a particular behavior.

Note: On Error GoTo -1 is useful in rare cases. In most cases using Resume Next is a better option as it clears the error and resumes the code the next time after the error occurs.

For example:

On Error GoTo -1

 

The Err Object

When an error occurs an Error object is created with the help of that we can get details about the Error that is the type of error and error number.

Err-object-created

 

The Er1 Function 

It is used to get the line number of the error.

er1-function

 

Err.Raise

We can create our errors with the help of this method. We can also Raise an error that will return a specific message depending on what kind of information is given to the code.

Syntax: Err. Raise [Number of the error],[Source of the error], [Description of the error]

From 1-512, several errors are reserved by VBA. So, we can use anything from 513 to 65535.

Let us consider the below example :

Err.Raise

 

Err.Clear

It is used to clear the number and type of the error from the Err. Object. It clears the description and numbers.’

We can use a clear method to explicitly clear the error object after an error has been handled.

Syntax: Err.Clear

Err.Clear function used

 

Error Function

It is used to print the description of the error from its number.

Printing-description-of-error

VBA IsError

VBA IsError is another method to handle error statements by testing for them. If an error occurs it returns a True or False value after testing an Expression for errors. 

Syntax: IsError(Expression)

where expression is what you to test if it is an error or not.

Let’s consider the below example:

IsError() function

IfError VBA

Users can handle errors in VBA using the Excel IfError function. 

This Function must be accessed through Worksheet Function.

Worksheet Function is the method of function class that helps you to access a lot of Standard Excel worksheet functions. All the Standard formulas in Excel start with (=) equal sign. Similarly, WorksheetFunction is a word that should be used to access the worksheet formula in VBA coding.

IfError Function

The above example will give an output value of Range “A1” If the value is an error it will give “0” as output.

VBA Error Handling in a Loop

The best way to error handle within a Loop is by using On Error Resume Next along with Err.Number to detect if an error has occurred,

Note: Remember to use Err.Clear to clear the error after each occurrence.

Below is the code that is used to divide two numbers( Column A by Column B) and output the result into Column C.

The result will be 0 if there’s an error. 

Sub test()

Dim cell As Range

On Error Resume Next

For each cell in Range( “A1: A10”)

‘Set cell value

Cell.offset(0,2).Value = cell.value/cell.offset(0,1).Value

‘If Cell.Value is Error then Default to 0

If Err.Number <>0 Then

cell.offset (0,2).Value =0

Err.Clear

End if

Next

End sub

VBA Error Trapping

VBA Error Trapping is just another term for VBA Error Handling

Conclusion

This article will help you to understand the concept of VBA Error Handling. Also, you can go through the different types of errors such as Syntax errors, compilation errors, Run time errors, and Logical errors. And What is the role of VBA Error Handling with different types of On Error Statement for example On Error Goto 0, On Error Resume Next, On Error GoTo [Label], and On Error GoTo -1. There are some more functions to handle the errors such as VBA IsError and IfError VBA. You can also learn some other important terms such as Err Object(which includes Er1 Function, Err.Raise, Err.Clear, Error Function), VBA Error Handling in a loop, and VBA Error Trapping.

FAQs on VBA Error Handling

What if Auto check syntax is disabled?

If Auto check syntax is disabled it will still highlight the line of code with the error but won’t show the error message.

How syntax errors and compiler errors are related? 

A syntax error is also a type of compiler error. A syntax error occurs when you press the enter button and VBA identifies that something is missing. Also, compilation error is detected when VBA doesn’t find anything missing while typing the code but it does when the code is compiled or executed.

What are parsing errors? 

Syntax errors are also known as parsing errors.

What is the difference between Err.Clear and OnError GoTo -1?

Although both are used to reset Err.Number to 0. But the only difference is Err. Clear does not reset the actual errors themselves. It only resets the Err. Number.

That means by using Err. Clear users will not be able to change the error handling setting.



Last Updated : 22 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads