Open In App

VBA Error Handling

Last Updated: 22 Sep, 2023

A

Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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.



A

News
Improve
Discuss
Do you want to advertise with us?Click here to know more

VBA Subroutine in Excel - How to Call Sub in VBA?

article_img
When a specified action is performed on a worksheet with the help of a collection of code known as a VBA Subroutine. It also helps to read an external file, also it can open other applications from Excel. A large piece of code can be broken into small parts so that we can manage it easily. Let's learn why to use submarines: Converts large piece of codes into small parts so that the computer ignores all kind of complexities that arises because of large codesReusability of code suppose we in a program have to access the database frequently so instead of writing the code again and again we can create a function to access the databaseSubroutines are self-documenting functions which means a coder can easily say what the program does by looking into the name of the function Naming Rules of SubroutinesIt can start with a letter or an underscore but it cannot start with a number or a special character.It cannot contain any space in the name.The name of the subroutine cannot be a keyword like Private, Sub, End, etc. Syntax Private Sub function_name( ByVal arg1 As String, ByVal arg2 As String) End Sub Syntax Explanation Code Action "Private Sub function_name(...)"Private is the keyword whic
Read More

ChatGPT Error Code 1020 - How to Fix Access Denied Error

article_img
The leading AI chatbot, ChatGPT has been making the headlines ever since it got launched. The language model aids the users in many ways by offering extensive services. The ChatGPT, developed by OpenAI offers has made it the number one AI service provider worldwide due to its technological abilities. However, there are a few technical shortcomings that even ChatGPT beholds. There are a few errors that you might have faced while using the ChatGPT app. One such common error is the “ChatGPT Error Code 1020: Access Denied” which could get displayed on your system due to multiple reasons. But you don’t need to worry about it. This error can be quickly fixed and you can get back to using your ChatGPT account in a few minutes. Let’s understand briefly the reasons behind this error and a few quick fixes for the same. What Is The ChatGPT Error Code 1020?The ChatGPT Error Code 1020 is an error that restricts you from accessing the ChatGPT website. This error shows up when your IP address has been flagged or blocked from browsing the ChatGPT website. ChatGPT uses a security firewall called Cloudflare which secures the website from any cybersecurity attacks. When ChatGPT faces this error, the
Read More

How to Fix ChatGPT "Upstream connect Error" - ChatGPT Error Code 111 (All Quick Fixes)

article_img
If you’re facing an Error “Upstream connect error or disconnect/reset before headers. Reset reason: remote connection failure, transport failure reason: delayed connect error: 111” while using ChatGPT, The ChatGPT "Upstream Connect Error" Code 111 typically indicates a connection failure between your device and OpenAI’s servers. This error often arises from network misconfigurations, server issues, or client-side problems. Below is a step-by-step guide to resolve it, based on troubleshooting methods from user reports and technical documentation.How to Fix ChatGPT Error Code 111Common Causes of Error Code 111Server-Side Issues: Temporary outages or maintenance on OpenAI’s servers.Network Restrictions: Firewalls, VPNs, or proxies blocking the connection.Docker/Container Misconfigurations: Incorrect network settings in Docker deployments (e.g., port conflicts).IP Blocking: Shared or flagged IP addresses triggering security restrictions.Client-Side Errors: Outdated browsers, cached data, or unstable internet connections.How to Fix ChatGPT Error Code 111: All Methods and FixesChatGPT Error Code 111 can be frustrating, but it’s often a temporary issue that can be resolved with simple tro
Read More

How to Use Select Case Statement in Excel VBA?

article_img
VBA in Excel stands for Visual Basic for Applications which is Microsoft's programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend. In this article, we are going to discuss how to use Select Case Statement in Excel VBA. Select Case Statement of Excel VBA The select case in VBA is like a detective that investigates an expression by checking it against different scenarios listed as Case Statements, each with its own conditions. When a scenario matches the expression, it's like solving a piece of the puzzle, and the corresponding code linked to that scenario is activated. Importantly, once a match is found, the detective stops investigating and moves on to executing the discovered code. Yet, if none of the scenarios match, it's like the detective hitting a dead end. In this situation, the code associated with the Case Else statement comes into play, offering a default solution or outcome. Syntax of the Select Case Statement of Excel VBAThe VBA Select Case Statement shares similarities with the Switch Case construct found in programming languages such as Java, C#, and PHP. In Excel VBA, this statement helps
Read More

Excel VBA Concatenation Operators

article_img
VBA in Excel stands for Visual Basic for Applications which is Microsoft's programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend. Concatenation means to join two or more data into a single data. There are various ways we can perform concatenation in Excel using built-in functions, operators, etc. Some helpful links to get more insights about concatenate and using VBA in Excel : Record Macros in ExcelCONCATENATE in ExcelHow to Create a Macro in Excel? In this article, we are going to see about concatenate operators and how to use VBA to concatenate strings as well as numbers. Implementation : In the Microsoft Excel tabs, select the Developer Tab. Initially, the Developer Tab may not be available. The Developer Tab can be enabled easily by a two-step process : Right-click on any of the existing tabs at the top of the Excel window.Now select Customize the Ribbon from the pop-down menu.In the Excel Options Box, check the box Developer to enable it and click on OK. Now, the Developer Tab is visible. Now, we need to open the Visual Basic Editor. There are two ways : Go to Developer and directly click on the
Read More

Excel VBA Comparison Operators

article_img
VBA in Excel stands for Visual Basic for Applications which is Microsoft's programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend. Some helpful links to get more insights about Macros, VBA in Excel : 1. Record Macros in Excel. 2. How to Create a Macro in Excel? In this article, we are going to discuss various comparison operators in Excel VBA. Implementation : In the Microsoft Excel tabs, select the Developer Tab. Initially, the Developer Tab may not be available. The Developer Tab can be enabled easily by a two-step process : Right-click on any of the existing tabs in the top of the Excel window.Now select Customize the Ribbon from the pop-down menu. The Excel Options Box, check the box Developer to enable it and click on OK. Now, the Developer Tab is visible. Now click on the Visual Basic option in the Developer tab and make a new module to write the program.Developer -> Visual Basic -> Tools -> Macros Now create a Macro and give any suitable name. This will open the Editor window where can write the code. Comparison Operators in Excel:S.No.OperatorsDefinition 1<> Not equal operator is
Read More

A

How to Use for Each Loop in Excel VBA?

A For Each loop is used to execute a statement or a set of statements for each element in an array or collection. Syntax: For Each element In group [ statements ] [ Exit For ] [ statements ] Next [ element ] The For...Each...Next statement syntax has the following three parts: PartDescriptionelement Required (Must be mentioned). Variable is used to iterate through the elements of the collection or array. For collections, the element can only be a Variant variable, a generic object variable, or any specific object variable. For arrays, the element can only be a Variant variable.groupRequired(Must be mentioned). Name of an object collection or array (except an array of user-defined types).statementOptional (May or may not be mentioned). One or more statements are executed on each item in the group. There are 4 basic steps to writing a For Each Next Loop in VBA: Declare a variable.Write the For Each Line with the variable and collection references.Add line(s) of code to repeat for each item in the collection.Write the Next line to terminate the loop. The For…Each block is entered if there is at least one element in the group. Upon entering the loop,
Read More

A

How to Use Do While Loop in Excel VBA?

article_img
A Do…While loop is used when we want to repeat certain set of statements as long as the condition is true. The condition may be checked at the starting or at the end of the loop Flowchart: Uses of Do-While loop: The Do While loop is used in two ways: Do…while loop which checks the condition at the STARTING of the loop.Do…while loop which checks the condition at the END of the loop. Syntax 1: Do While condition [statements] [Exit Do] [statements] Loop Syntax 2: Do While [statements] [Exit Do] [statements] Loop conditionImplementing a Do While loop: Follow the below steps to implement a Do-While loop: Step 1: Define a Macro Private Sub Demo_Loop() End Sub Step 2: Define variables j=2 i=1 Step 3: Write Do While Loop. You can write condition at the beginning or at the end Do While i < 5 Step 4: Write statements to be executed in loop msgbox "Table of 2 is : " & (j*i) i=i+1 Step 5: End loop. Now let's take a look at some of the examples. Example 1: Do…while loop which checks the condition at the STARTING of the loop. The below example uses Do…while loop to check the condition at the starting of the loop. The statements inside the loop are executed, only if the condition is True
Read More

How to Use For Next Loop in Excel VBA?

article_img
If you are familiar with the programming you must have an idea of what a loop is, In computer programming, a loop is a sequence of statements that are repeated until a specific condition is satisfied. In Excel VBA the "For Next" loop is used to go through a block of code a specific number of times. Syntax: For counter = start to end [step count] [code block to execute] statement 1 statement 2 statement 3 . . statement n Next [counter] Here we can use the counter or any other variable to run them as many times as we need. Example: When you are displaying numbers from 1 to 10 you may want to set the value of a variable to 1 and display it 10 times, increasing its value by 1 on each loop iteration. The same logic is used in VBA. We specify how many times we have to run the loop, and then specify what code should our loop execute each time the loop runs. A loop has 3 parts the first one is an initialization, the second is the condition under which the loop runs, and the last is increment or decrement. The flow of the control in for loop:The For step is executed first. This step allows you to initialize any loop control variables and increment the step counter variable.Then the second
Read More

How to Get Length of Array in Excel VBA?

article_img
We use UBound and LBound functions to get the length of an Array in Excel VBA. In this article, we will discuss them in detail. Syntax: UBound() function UBound (arrayname, [ dimension ]) Parameters: arrayname: required. Array variable namedimension: optional Returns: Return upper limit of an array dimension. Syntax: LBound() Function LBound (arrayname, [ dimension ]) Parameters: arrayname : required. Array variable namedimension : optional Returns: Return lower limit of an array dimension Sample Data: VBA Code to get the length of Array (one-dimensional array): Declare Variables: Declaring a customer array with the size of 10. Sub oneDimArrayLength() ' Array variable Declaration Dim customer (1 To 10) As String Assign values to array elements customer(1) = "ANTON" customer(2) = "BERGS" customer(3) = "BOLID" customer(4) = "KOENE" customer(5) = "FRANS" Use UBound function to get the size of an array and Message box to display the result 'Message box to popup length of 1D array MsgBox "Array has " & UBound(customer) & " element(s)." End Sub To Run VBA Code Press Alt+F8 to popup macro window. Select " oneDimArrayLength" and Click Run button. Output VBA Code to get the length
Read More
three90RightbarBannerImg