In this Article
- VBA Errors Cheat Sheet
- Errors
- VBA Error Handling
- VBA On Error Statement
- On Error GoTo 0
- On Error Resume Next
- Err.Number, Err.Clear, and Catching Errors
- Error Handling with Err.Number
- On Error GoTo Line
- On Error Exit Sub
- Err.Clear, On Error GoTo -1, and Resetting Err.Number
- VBA On Error MsgBox
- VBA IsError
- If Error VBA
- VBA Error Types
- Runtime Errors
- Syntax Errors
- Compile Errors
- Debug > Compile
- OverFlow Error
- Other VBA Error Terms
- VBA Catch Error
- VBA Ignore Error
- VBA Throw Error / Err.Raise
- VBA Error Trapping
- VBA Error Message
- VBA Error Handling in a Loop
- VBA Error Handling in Access
VBA Errors Cheat Sheet
Errors
On Error – Stop code and display error
On Error Goto 0
On Error – Skip error and continue running
On Error Resume Next
On Error – Go to a line of code [Label]
On Error Goto [Label]
Clears (Resets) Error
On Error GoTo –1
Show Error number
MsgBox Err.Number
Show Description of error
MsgBox Err.Description
Function to generate own error
Err.Raise
See more VBA “Cheat Sheets” and free PDF Downloads
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 Runtime Errors are errors that occur during code execution. Examples of runtime errors include:
- Referencing a non-existent workbook, worksheet, or other object (Run-time Error 1004)
- Invalid data ex. referencing an Excel cell containing an error (Type Mismatch – Run-time Error 13)
- Attempting to divide by zero
VBA On Error Statement
Most VBA error handling is done with the On Error Statement. The On Error statement tells VBA what to do if it encounters an error. There are three On Error Statements:
- On Error GoTo 0
- On Error Resume Next
- On Error GoTo Line
On Error GoTo 0
On Error GoTo 0 is VBA’s default setting. You can restore this default setting by adding the following line of code:
On Error GoTo 0
When an error occurs with On Error GoTo 0, VBA will stop executing code and display its standard error message box.
Often you will add an On Error GoTo 0 after adding On Error Resume Next error handling (next section):
Sub ErrorGoTo0()
On Error Resume Next
ActiveSheet.Shapes("Start_Button").Delete
On Error GoTo 0
'Run More Code
End Sub
On Error Resume Next
On Error Resume Next tells VBA to skip any lines of code containing errors and proceed to the next line.
On Error Resume Next
Note: On Error Resume Next does not fix an error, or otherwise resolve it. It simply tells VBA to proceed as if the line of code containing the error did not exist. Improper use of On Error Resume Next can result in unintended consequences.
A great time to use On Error Resume Next is when working with objects that may or may not exist. For example, you want to write some code that will delete a shape, but if you run the code when the shape is already deleted, VBA will throw an error. Instead you can use On Error Resume Next to tell VBA to delete the shape if it exists.
On Error Resume Next
ActiveSheet.Shapes("Start_Button").Delete
On Error GoTo 0
Notice we added On Error GoTo 0 after the line of code containing the potential error. This resets the error handling.
In the next section we’ll show you how to test if an error occurred using Err.Number, giving you more advanced error handling options.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Err.Number, Err.Clear, and Catching Errors
Instead of simply skipping over a line containing an error, we can catch the error by using On Error Resume Next and Err.Number.
Err.Number returns an error number corresponding with the type of error detected. If there is no error, Err.Number = 0.
For example, this procedure will return “11” because the error that occurs is Run-time error ’11’.
Sub ErrorNumber_ex()
On Error Resume Next
ActiveCell.Value = 2 / 0
MsgBox Err.Number
End Sub
Error Handling with Err.Number
The true power of Err.Number lies in the ability to detect if an error occurred (Err.Number <> 0). In the example below, we’ve created a function that will test if a sheet exists by using Err.Number.
Sub TestWS()
MsgBox DoesWSExist("test")
End Sub
Function DoesWSExist(wsName As String) As Boolean
Dim ws As Worksheet
On Error Resume Next
Set ws = Sheets(wsName)
'If Error WS Does not exist
If Err.Number <> 0 Then
DoesWSExist = False
Else
DoesWSExist = True
End If
On Error GoTo -1
End Function
Note: We’ve added a On Error GoTo -1 to the end which resets Err.Number to 0 (see two sections down).
With On Error Resume Next and Err.Number, you can replicate the “Try” & “Catch” functionality of other programming languages.
On Error GoTo Line
On Error GoTo Line tells VBA to “go to” a labeled line of code when an error is encountered. You declare the Go To statement like this (where errHandler is the line label to go to):
On Error GoTo errHandler
and create a line label like this:
errHandler:
Note: This is the same label that you’d use with a regular VBA GoTo Statement.
Below we will demonstrate using On Error GoTo Line to Exit a procedure.
On Error Exit Sub
You can use On Error GoTo Line to exit a sub when an error occurs.
You can do this by placing the error handler line label at the end of your procedure:
Sub ErrGoToEnd()
On Error GoTo endProc
'Some Code
endProc:
End Sub
or by using the Exit Sub command:
Sub ErrGoToEnd()
On Error GoTo endProc
'Some Code
GoTo skipExit
endProc:
Exit Sub
skipExit:
'Some More Code
End Sub
Err.Clear, On Error GoTo -1, and Resetting Err.Number
After an error is handled, you should generally clear the error to prevent future issues with error handling.
After an error occurs, both Err.Clear and On Error GoTo -1 can be used to reset Err.Number to 0. But there is one very important difference: Err.Clear does not reset the actual error itself, it only resets the Err.Number.
What does that mean? Using Err.Clear, you will not be able to change the error handling setting. To see the difference, test out this code and replace On Error GoTo -1 with Err.Clear:
Sub ErrExamples()
On Error GoTo errHandler:
'"Application-defined" error
Error (13)
Exit Sub
errHandler:
' Clear Error
On Error GoTo -1
On Error GoTo errHandler2:
'"Type mismatch" error
Error (1034)
Exit Sub
errHandler2:
Debug.Print Err.Description
End Sub
Typically, I recommend always using On Error GoTo -1, unless you have a good reason to use Err.Clear instead.
VBA On Error MsgBox
You might also want to display a Message Box on error. This example will display different message boxes depending on where the error occurs:
Sub ErrorMessageEx()
Dim errMsg As String
On Error GoTo errHandler
'Stage 1
errMsg = "An error occured during the Copy & Paste stage."
'Err.Raise (11)
'Stage 2
errMsg = "An error occured during the Data Validation stage."
'Err.Raise (11)
'Stage 3
errMsg = "An error occured during the P&L-Building and Copy-Over stage."
Err.Raise (11)
'Stage 4
errMsg = "An error occured while attempting to log the Import on the Setup Page"
'Err.Raise (11)
GoTo endProc
errHandler:
MsgBox errMsg
endProc:
End Sub
Here you would replace Err.Raise(11) with your actual code.
VBA IsError
Another way to handle errors is to test for them with the VBA ISERROR Function. The ISERROR Function tests an expression for errors, returning TRUE or FALSE if an error occurs.
Sub IsErrorEx()
MsgBox IsError(Range("a7").Value)
End Sub
VBA Programming | Code Generator does work for you!
If Error VBA
You can also handle errors in VBA with the Excel IFERROR Function. The IFERROR Function must be accessed by using the WorksheetFunction Class:
Sub IfErrorEx()
Dim n As Long
n = WorksheetFunction.IfError(Range("a10").Value, 0)
MsgBox n
End Sub
This will output the value of Range A10, if the value is an error, it will output 0 instead.
VBA Error Types
Runtime Errors
As stated above:
VBA Runtime Errors are errors that occur during code execution. Examples of runtime errors include:
- Referencing a non-existent workbook, worksheet, or other object
- Invalid data ex. referencing an Excel cell containing an error
- Attempting to divide by zero
You can “error handle” runtime errors using the methods discussed above.
Syntax Errors
VBA Syntax Errors are errors with code writing. Examples of syntax errors include:
- Mispelling
- Missing or incorrect punctuation
The VBA Editor identifies many syntax errors with red highlighting:
The VBA Editor also has an option to “Auto Syntax Check”:
When this is checked, the VBA Editor will generate a message box alerting you syntax errors after you enter a line of code:
I personally find this extremely annoying and disable the feature.
Compile Errors
Before attempting to run a procedure, VBA will “compile” the procedure. Compiling transforms the program from source code (that you can see) into executable form (you can’t see).
VBA Compile Errors are errors that prevent the code from compiling.
A good example of a compile error is a missing variable declaration:
Other examples include:
- For without Next
- Select without End Select
- If without End If
- Calling a procedure that does not exist
Syntax Errors (previous section) are a subset of Compile Errors.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Debug > Compile
Compile errors will appear when you attempt to run a Procedure. But ideally, you would identify compile errors prior to attempting to run the procedure.
You can do this by compiling the project ahead of time. To do so, go to Debug > Compile VBA Project.
The compiler will “go to” the first error. Once you fix that error, compile the project again. Repeat until all errors are fixed.
You can tell that all errors are fixed because Compile VBA Project will be grayed out:
OverFlow Error
The VBA OverFlow Error occurs when you attempt to put a value into a variable that is too large. For example, Integer Variables can only contain values between -32,768 to 32,768. If you enter a larger value, you’ll receive an Overflow error:
Instead, you should use the Long Variable to store the larger number.
Other VBA Error Terms
VBA Catch Error
Unlike other programming languages, In VBA there is no Catch Statement. However, you can replicate a Catch Statement by using On Error Resume Next and If Err.Number <> 0 Then. This is covered above in Error Handling with Err.Number.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
VBA Ignore Error
To ignore errors in VBA, simply use the On Error Resume Next statement:
On Error Resume Next
However, as mentioned above, you should be careful using this statement as it doesn’t fix an error, it just simply ignores the line of code containing the error.
VBA Throw Error / Err.Raise
To through an error in VBA, you use the Err.Raise method.
This line of code will raise Run-time error ’13’: Type mismatch:
Err.Raise (13)
VBA Error Trapping
VBA Error Trapping is just another term for VBA Error Handling.
VBA Error Message
A VBA Error Message looks like this:
When you click ‘Debug’, you’ll see the line of code that is throwing the error:
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
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 (Remember to use Err.Clear to clear the error after each occurrence).
The example below will divide two numbers (Column A by Column B) and output the result into Column C. If there’s an error, the result will be 0.
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 Handling in Access
All of the above examples work exactly the same in Access VBA as in Excel VBA.
Function DelRecord(frm As Form)
'this function is used to delete a record in a table from a form
On Error GoTo ending
With frm
If .NewRecord Then
.Undo
Exit Function
End If
End With
With frm.RecordsetClone
.Bookmark = frm.Bookmark
.Delete
frm.Requery
End With
Exit Function
ending:
End
End Function
Excel VBA On Error Resume Next
Error Handling is a very useful & significant mechanism for programming languages like VBA Error control or prevention which is an aspect of Error handling which means taking effective & significant measures inside a VBA script to avoid the occurrence of error pop up message. The Excel VBA On Error Resume Next statement ignores the code line that causes an error and continues or routes execution to the next line following the line that caused the error.
NOTE: On Error Resume Next statement doesn’t fix the runtime errors, it’s an error ignoring where VB program execution will continue from the line which has caused the runtime error.
Basically, On error resume next is used when you want to ignore the error & continue or resume the code execution to the next cell.
Types of Errors in VBA
Below are the different types of Errors in VBA:
- Syntax Error or Parsing error.
- Compile Or Compilation Error.
- Runtime Error.
- Logical Error.
The above errors can be rectified with the help of debugging & ‘On Error’ Statements in a code. The Runtime Error can be prevented with the help of On Error Resume Next.
VBA Runtime Error:
Before the explanation of On Error Resume Next, you should be aware of runtime error when impossible mathematical statements or terms present in a statement, then this runtime error occurs.
Examples of Excel VBA On Error Resume Next
Below are the different examples of On Error Resume Next in Excel VBA:
You can download this VBA On Error Resume Next Excel Template here – VBA On Error Resume Next Excel Template
VBA On Error Resume Next – Example #1
Here, an error will be ignored, and the execution of code will move on. In the below-mentioned example, 6 can’t be divided by zero, if you run it without entering On Error Resume Next statement, then below mentioned runtime error occurs.
Code:
Sub RUNTIME_1() MsgBox 6 / 0 End Sub
If On Error Resume Next in entered at the top of code after SUB statement, it ignores runtime error and moves on to next statement, results in an output of 6/2 (Popup message box with result of it).
Code:
Sub RUNTIME_2() On Error Resume Next MsgBox 6 / 0 MsgBox 6 / 2 End Sub
VBA On Error Resume Next – Example #2
I can use On Error Resume Next anywhere in the code from the beginning to the end. In the below-mentioned example, I have to make a 3 calculation i.e.
9/3 =?
9/0 =?
9/2 =?
In the above-mentioned example, you can observe a second calculation where any number can’t be divided by zero, i.e. 9 can’t be divided by zero in the second step. Suppose if you run the macro without entering On Error Resume Next statement, now I can execute the code step by step with the help of step into or F8 key to understand how it works.
Now, I run the above code, by clicking on step Into option or F8 key frequently, step by step. I just copy the above code and start running it step by step, for the first step of calculation message box 3 appears.
Code:
Sub RUNTIME_3() MsgBox 9 / 3 MsgBox 9 / 0 MsgBox 9 / 2 End Sub
When I run the second line of code, then below mentioned runtime error occurs at the second step of a code, where any number can’t be divided by zero, i.e. 9 can’t be divided by zero in the second step.
Code:
Sub RUNTIME_3() MsgBox 9 / 3 MsgBox 9 / 0 MsgBox 9 / 2 End Sub
Now, if I even click on debug, it can’t proceed further, where it will take me to the second line of code (It gets highlighted in yellow color), where I need to do the correction. So, here, if further click on Step Into option or F8 key, the third calculation in this code will not get executed.
To rectify or handle this runtime error, I have to use or execute the OnError Resume Next statement above a second code or at the beginning of code below the substatement. so that it will skip that line of code and moves on to the third step of code and calculate the value.
Code:
Sub RUNTIME_30() MsgBox 9 / 3 On Error Resume Next MsgBox 9 / 0 MsgBox 9 / 2 End Sub
OR
Sub RUNTIME_31() On Error Resume Next MsgBox 9 / 3 MsgBox 9 / 0 MsgBox 9 / 2 End Sub
Now, I have added on error resume next statement to the code, where you can use any one of above code, if you run it step by step, you will get a two-message popup, one is the output first code and third code calculation. On Error Resume Next will ignore the runtime error in the second code and move on to the third code.
VBA On Error Resume Next – Example #2
We will now see the Combination of On Error Resume Next with Error GoTo 0. In the below code, it will ignore errors until it reaches On Error GoTo 0 statement. After On Error GoTo 0 statement, the code goes back or proceed to normal error checking and triggers the expected error ahead.
Code:
Sub onError_Go_to_0_with_Resume_next() On Error Resume Next Kill "C:TempFile.exe" On Error GoTo 0 Range("A1").Value = 100 / "PETER" End Sub
When I run the above code, it will showcase the division error i.e. Type mismatch (numeric value can’t be divided by text).
Now, you can save your workbook as an “Excel macro-enabled workbook”. By clicking on save as at the left corner of the worksheet.
when you open this excel file again, you can use below-mentioned shortcut key i.e.
Function + Alt + F11 short cut key helps you out to access all the created macro code of the workbook. Function + Alt + F8 short cut key helps you out to open a “Macro” dialog box window, which contains all the macro names, where you can run a specific macro code of your choice.
Things to Remember
- Run time error will be silently trapped and stored in the global Err object
- On Error Resume Next usually prevent an interruption in code execution.
- Error object properties (Err Object) get cleared automatically when Resume Next is used in an error-handling routine
Recommended Articles
This is a guide to VBA On Error Resume Next. Here we discuss different types of Error in VBA Excel along with some practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA Macros
- VBA DateDiff
- VBA Protect Sheet
- VBA Environ
Обработка ошибок в VBA Excel с помощью оператора On Error. Синтаксис выражений с оператором On Error. Пример кода с простым обработчиком ошибок.
On Error – это оператор, который используется для отслеживания ошибок во время исполнения кода VBA. При возникновении ошибки On Error передает информацию о ней в объект Err и включает программу обработки ошибок, начинающуюся с указанной строки.
В первую очередь, обработчик ошибок нужен для пользователей файлов Excel с кодами VBA. Любая ошибка приводит к прекращению выполнения программы, открытию редактора VBA с непонятным для пользователя сообщением или даже к полному зависанию приложения.
Обработчик ошибок позволяет завершить выполнение программы при возникновении ошибки и вывести сообщение пользователю с ее описанием.
Синтаксис выражений с On Error
Включает алгоритм обнаружения ошибок и, в случае возникновения ошибки, передает управление операторам обработчика ошибок с указанной в выражении строки. Stroka – это метка, после которой расположены операторы обработчика ошибок.
Включает алгоритм обнаружения ошибок и, в случае возникновения ошибки, передает управление оператору, следующему за оператором, вызвавшем ошибку.
Отключает любой включенный обработчик ошибок в текущей процедуре.
Простой обработчик ошибок
Шаблон простейшего обработчика ошибок:
Sub Primer() On Error GoTo Stroka ‘Блок операторов процедуры Exit Sub Stroka: MsgBox «Произошла ошибка: « & Err.Description End Sub |
Оператор On Error GoTo
размещается в начале процедуры, метка и обработчик ошибок – в конце процедуры. Название метки можно сменить на другое, в том числе на кириллице.
Оператор Exit Sub
обеспечивает выход из процедуры, если блок операторов выполнен без ошибок. Для вывода описания ошибки используется свойство Description
объекта Err
.
Примеры обработки ошибок
Пример 1
Деление на ноль:
Sub Primer1() On Error GoTo Инструкция Dim a As Double a = 45 / 0 Exit Sub Instr: MsgBox «Произошла ошибка: « & Err.Description End Sub |
Результат выполнения кода VBA Excel с обработчиком ошибок:
Пример 2
Выход за границы диапазона:
Sub Primer2() On Error GoTo Instr Dim myRange As Range Set myRange = Range(«A1:D4»).Offset(—2) Exit Sub Instr: MsgBox «Произошла ошибка: « & Err.Description End Sub |
Результат выполнения кода VBA Excel с оператором On Error GoTo
:
Пример использования выражений On Error Resume Next
и On Error GoTo 0
смотрите в статье: Отбор уникальных значений с помощью Collection.
VBA On Error Resume Next is an error handler statement. If the error occurs while running the code, you can use this statement to resume the next line of code by ignoring the error message instead of showing an error.
Those who write codes regularly in excel VBA know they may get errors even after writing proficient codes, but they want to ignore that error and keep running with the next lines of code. An example of getting an error message is when the VLOOKUP worksheet functionThe VLOOKUP excel function searches for a particular value and returns a corresponding match based on a unique identifier. A unique identifier is uniquely associated with all the records of the database. For instance, employee ID, student roll number, customer contact number, seller email address, etc., are unique identifiers.
read more does not find the lookup value from the table array. Therefore, it would not return the #N/A error. Rather, it will throw the error: “Unable to get the VLOOKUP property of the worksheet function class.”
Table of contents
- Excel VBA On Error Resume Next
- What does On Error Resume Next Do in VBA?
- Example #1
- Example #2
- Things to Remember here
- Recommended Articles
- What does On Error Resume Next Do in VBA?
It is very difficult to fix the bug if you do not know why we are getting this error. In VBA, we have a feature called “On Error Resume Next.”
What Does On Error Resume Next Do in VBA?
There are certain areas as a coder. First, we know this will surely give an error message, but we need to ignore this error to keep going through the code. So, how to ignore that error is a common doubt everybody has.
We can ignore the error using the VBA On Error Resume Next statement and resume the next line of code.
You can download this VBA On Error Resume Next Excel Template here – VBA On Error Resume Next Excel Template
Example #1
Assume you have many worksheets, and you are hiding some of them as part of the VBA project. For example, below are the worksheets we have in our worksheet.
We have written codes to hide “Sales” and “Profit” sheets, and below is the code.
Code:
Sub On_Error() Worksheets("Sales").Visible = xlVeryHidden Worksheets("Profit 2019").Visible = xlVeryHidden Worksheets("Profit").Visible = xlVeryHidden End Sub
We will start running the code line by line using the F8 key.
If we press the F8 key one more time, it will hide the sheet named “Sales.”
Now, press the F8 key one more time and see what happens.
We have got a “Subscript out of rangeSubscript out of range is an error in VBA that occurs when we attempt to reference something or a variable that does not exist in the code. For example, if we do not have a variable named x but use the msgbox function on x, we will receive a subscript out of range error.read more” error because the current line of code says the below.
Worksheets("Profit 2019").Visible = xlVeryHidden
It is trying to hide the worksheet named “Profit 2019,” but there is no worksheet by the name of “Profit 2019”.
In these cases, if the worksheet doesn’t exist in the workbook, we need to ignore the error and continue to run the code by ignoring the “Subscript out of range” error.
The next line in the code says
Worksheets("Profit").Visible = xlVeryHidden
This worksheet exists in this workbook, so we cannot move to this line of code without ignoring the error.
We need to add the “On Error Resume Next” statement to ignore this error.
Code:
Sub On_Error() On Error Resume Next Worksheets("Sales").Visible = xlVeryHidden Worksheets("Profit 2019").Visible = xlVeryHidden Worksheets("Profit").Visible = xlVeryHidden End Sub
As you can see above, we have added the statement at the top of the code before any lines start. Now, run the code and see what happens.
Now, we are in the line given the error previously, press the F8 key, and see what happens.
We have jumped to the next line of code without showing any error because of the statement we have added at the top, which is the “On Error Resume Next” VBA statement.
Example #2
We will see how to use this statement with one more example. Look at the below data structure for this example.
We have two tables above. The first table has “Emp Name” and their salary details in the second table. Unfortunately, we have only “Emp Name.” So by using VLOOKUP, we need to fetch the salary details from the left side table.
Below is the code we had written to fetch the details.
Code:
Sub On_Error1() Dim k As Long For k = 2 To 8 Cells(k, 6).Value = WorksheetFunction.VLookup(Cells(k, 5), Range("A:B"), 2, 0) Next k End Sub
Now, run the code line by line and see what happens.
Upon running the first cell code, we got the result for the first employee. Repeat the same for the second employee as well.
This time we got the error message. Let us look at the second employee’s name on the table.
The second employee’s name is “Gayathri,” but this name does not exist in the first table, so the VBA VLOOKUP functionThe functionality of VLOOKUP in VBA is similar to that of VLOOKUP in a worksheet, and the method of using VLOOKUP in VBA is through an application. Method WorksheetFunctionread more does not return a #N/A error when the VLOOKUP does not find the lookup value from the table. Rather, it gives the above error message.
Our aim is if the employee name is unfound in the table, then we need an empty cell for that employee, ignore the error, and give results for the remaining names.
We need to add the “On Error Resume Next” statement inside the loop.
Code:
Sub On_Error1() Dim k As Long For k = 2 To 8 On Error Resume Next Cells(k, 6).Value = WorksheetFunction.VLookup(Cells(k, 5), Range("A:B"), 2, 0) Next k End Sub
Now, run the code and see the result.
The two employee names: “Gayathri” and “Karanveer,” are not on the list. So, those line codes must have encountered an error since we have added an error handler statement of “On Error Resume Next.” It has ignored that line of code and resumed for the next employee.
Things to Remember here
- The “On Error Resume Next” is the error handler statement when we need to ignore the known error.
- If we want to ignore the error message only for a specific code set, close the On Error Resume Next statement by adding the “On Error GoTo 0” statement.
Recommended Articles
This article has been a guide to VBA On Error Resume Next. Here, we discuss how to ignore errors and resume the next line of code in Excel VBA with examples and a downloadable Excel template. You can learn more about VBA functions from the following articles: –
- VBA Split String into Array
- VBA Square Root
- Type Mismatch Error in VBA
- 1004 Error in VBA
Обработка ошибок Excel VBA
В VBA, когда мы работаем с кодами, мы можем столкнуться со многими различными типами ошибок, и способ устранения этих ошибок известен как обработка ошибок, теперь могут быть некоторые ошибки, которые сделаны в синтаксисе, который сам выделяет это, но когда есть какая-то ошибка который выходит за пределы диапазона или что-то, чего не существует Excel дает нам всплывающее окно для того же самого, важно знать, какой код ошибки для какой ошибки, чтобы идентифицировать ошибку в коде.
В Excel VBA при выполнении любого набора кодов мы получаем какие-то ошибки. Некоторые из этих ошибок являются синтаксическими; некоторые из них являются неисполняемыми ошибками. Синтаксическая ошибка, сделанная пользователем, выделяется красным цветом самим Excel. Но когда возникает какая-либо другая ошибка времени выполнения, как мы с ней справимся и как выйти за рамки этого, мы рассмотрим в этой статье.
Помимо синтаксических ошибок, другие ошибки времени выполнения необходимо обрабатывать при выполнении любого набора кодов. Во-первых, позвольте мне привести пример того, как возникает другая ошибка времени выполнения. Взгляните на приведенный ниже код,
Это пример кода, который при выполнении вернет то, что написано в функции msgbox. Но, как мы видим, во второй строке кода есть 4/0, что невозможно с математической точки зрения, поэтому он вернет ошибку времени выполнения. Давайте выполним приведенный выше код и увидим ошибку, которую мы получим.
Это ошибка, которую мы получаем при выполнении данного кода. Теперь, как мы обрабатываем эту ошибку, производится обработкой ошибок.
Существует два метода обработки ошибок:
- При ошибке Перейти к и
- При ошибке Возобновить дальше.
Объяснение
Как объяснялось выше, мы получаем много типов ошибок в VBA. Некоторые из них являются синтаксисом, а некоторые — временем выполнения. Синтаксические ошибки уже выделены красным цветом, например, см. скриншот ниже,
В то время как другие ошибки времени выполнения. По сути, Excel выполняет следующие три действия: либо показывает ошибку, либо игнорирует эту ошибку, либо показывает определенный набор инструкций. Для выполнения таких задач нам нужно давать инструкции, и это называется обработкой ошибок.
Как обрабатывать ошибки в коде VBA?
Вы можете скачать этот шаблон Excel для обработки ошибок VBA здесь — Шаблон Excel для обработки ошибок VBA
Пример №1
В качестве первого примера возьмем первый код, который мы взяли в качестве демонстрации. В приведенном выше примере мы видели, что код выдает ошибку времени выполнения во второй функции msgbox.
Напишите следующий код после открытия подфункции,
Код:
Sub Sample() On Error Resume Next MsgBox 4 / 2 MsgBox 4 / 0 MsgBox 4 / 1 End Sub
Теперь, когда мы выполняем приведенный выше код, мы видим, что строка кода с ошибкой не выполняется. Excel пропускает эту строку и возобновляет работу на следующей строке.
Существует еще один способ обработки ошибки — VBA. Заявление о переходеОператор VBA GoTo позволяет перейти к строке кода, пропуская все ошибки между ними. Существует два типа операторов GOTO: один — выбрать любой диапазон рабочего листа в указанной книге, а другой — обработчик ошибок.читать далее. Мы предоставляем Excel в качестве места назначения для перехода при обнаружении ошибки. Вместо предыдущего кода обработки ошибок мы вставили, запишите следующий код,
Код:
Sub Sample() On Error GoTo az MsgBox 4 / 2 MsgBox 4 / 0 MsgBox 4 / 1 End Sub
Мы даем Excel Az в качестве пункта назначения, к которому можно перейти, если он обнаружит ошибку. Теперь после msgbox напишите еще один код, как показано ниже,
Код:
Sub Sample() On Error GoTo az MsgBox 4 / 2 MsgBox 4 / 0 MsgBox 4 / 1 Done: Exit Sub
Теперь нам нужно определить пункт назначения az как то, что он должен делать, когда Excel находит ошибку в коде.
Код:
Sub Sample() On Error GoTo az MsgBox 4 / 2 MsgBox 4 / 0 MsgBox 4 / 1 Done: Exit Sub az: MsgBox "This is an error " & Err.Description End Sub
Теперь, когда мы запускаем этот код, мы видим отображаемый результат.
Это первый результат окна сообщения, и, поскольку мы знаем, что у нас есть ошибка в следующей строке нашего кода, давайте посмотрим результат, который даст Excel.
err.description выше в коде помогает нам точно показать, какая ошибка произошла в нашем коде.
Пример #2
Мы научились обрабатывать ошибки в наших кодах. Давайте посмотрим на другой пример того, как обрабатывать ошибки. Рассмотрим следующий код в качестве нашего второго примера.
У нас есть чем-то похожая ошибка из примера 1. Ошибка в строке d = i/b. Теперь мы будем обрабатывать эти ошибки, используя два описанных выше метода.
Напишите следующий код после открытия подфункции,
Код:
Sub Sample2() On Error Resume Next bx Dim i As Integer, b As Integer, c As Integer, d As Integer i = 2 b = 0 c = i + b MsgBox c d = i / b MsgBox d End Sub
Теперь, когда мы выполняем наш код, мы видим, что он игнорирует вторую строку и просто отображает значение для C.
Вышеупомянутый обработчик ошибок был следующим для возобновления, и теперь мы будем использовать Go to, в котором мы скажем, что превосходим пункт назначения для перехода, когда он обнаруживает ошибку. Запишите следующий код,
Код:
Sub Sample2() On Error GoTo bx Dim i As Integer, b As Integer, c As Integer, d As Integer i = 2 b = 0 c = i + b MsgBox c d = i / b MsgBox d
bx — это пункт назначения, который выдается при возникновении ошибки после того, как msgbox D запишет следующий код:
Код:
Sub Sample2() On Error GoTo bx Dim i As Integer, b As Integer, c As Integer, d As Integer i = 2 b = 0 c = i + b MsgBox c d = i / b MsgBox d DOne: Exit Sub
Теперь нам нужно определить пункт назначения Bx, что он должен делать при обнаружении ошибки. Поэтому запишите следующий код:
Код:
Sub Sample2() On Error GoTo bx Dim i As Integer, b As Integer, c As Integer, d As Integer i = 2 b = 0 c = i + b MsgBox c d = i / b MsgBox d DOne: Exit Sub bx: MsgBox " This is another Error " & Err.Description End Sub
Теперь, когда мы выполняем код, мы видим, что Excel сначала дает нам значение для C.
Теперь на другом этапе он даст нам подсказку, которую мы ему предоставили, когда он обнаружит ошибку.
Вот как мы обрабатываем обычную среду выполнения ошибки в экселеОшибки в Excel распространены и часто возникают во время применения формул. Список из девяти наиболее распространенных ошибок Excel: #DIV/0, #N/A, #NAME?, #NULL!, #NUM!, #REF!, #VALUE!, #####, Circular Reference.читать далее VBA.
То, что нужно запомнить
Есть несколько вещей, которые нам нужно помнить об обработке ошибок:
- При следующем возобновлении ошибки игнорирует ошибку.
- On Error GoTo Отображает пункт назначения excel при обнаружении ошибки.
- Описание используется для отображения точной ошибки, возникшей у пользователя.
УЗНАТЬ БОЛЬШЕ >>
Post Views: 634
Активизирует подпрограмму обработки ошибок и указывает положение подпрограммы в процедуре; используется также для отключения подпрограммы обработки ошибок.
- On Error GoTo строка — Активизирует подпрограмму обработки ошибок, начало которой определяется обязательным аргументом строка, значением которого может быть любая метка строки или номер строки. Если возвращается ошибка выполнения, управление передается на указанную строку и запускается обработчик ошибок. Аргумент строка должен определять строку в той же процедуре, в которой находится инструкция On Error; в противном случае возникает ошибка компиляции.
- On Error Resume Next — Указывает, что возникновение ошибки выполнения приводит к передаче управления на инструкцию, непосредственно следующую за инструкцией, при выполнении которой возникла ошибка. Рекомендуется при доступе к объектам использовать эту форму инструкции, а не On Error GoTo.
- On Error GoTo 0 — Отключает любой активизированный обработчик ошибок в текущей процедуре.
Замечания
Если не выполнена инструкция On Error, то любая ошибка выполнения является фатальной; это означает, что выводится сообщение об ошибке и выполнение программы прекращается.
«Включенным» обработчиком ошибок называют подпрограмму, которая указана в инструкции On Error; «активным» обработчиком ошибок является включенный обработчик ошибок, который обрабатывает текущую ошибку. Если ошибка возникает в самом обработчике ошибок (в промежутке между возникновением ошибки и выполнением инструкции Resume, Exit Sub, Exit Function или Exit Property), то обработчик ошибок, определенный в текущей процедуре, не может обработать ошибку. Управление в этом случае возвращается в вызывающую процедуру; если в вызывающей процедуре включен обработчик ошибок, то обработка ошибки передается ему. Если этот обработчик ошибок является в данный момент активным, т.е. уже обрабатывает ошибку, то управление снова передается назад в вызывающую процедуру и т.д. до тех пор, пока не будет найден включенный, но не активный обработчик ошибок. Если включенный, но неактивный обработчик ошибок найден не будет, ошибка становится фатальной в том месте программы, в котором она впервые возникла. При каждой передаче управления обработчиком ошибок в вызывающую процедуру эта процедура становится текущей. После завершения обработки ошибки обработчиком в любой процедуре возобновляется выполнение текущей процедуры с той ее части, которая указана в инструкции Resume.
Подпрограмма обработки ошибок не может быть процедурой Sub или Function. Эта подпрограмма должна быть частью программы, которая отмечается с помощью метки строки или номера строки.
Для определения причины ошибки в подпрограммах обработки ошибок используют значение свойства Number объекта Err. Необходимо обеспечить в подпрограммах обработки ошибок проверку или сохранение существенных значений свойств объекта Err перед тем, как может возникнуть новая ошибка или перед вызовом процедуры, в которой может возникнуть новая ошибка. Значения свойств объекта Err описывают последнюю ошибку. Текст сообщения об ошибке, соответствующего коду ошибки Err.Number содержится в свойстве Err.Description.
Конструкция On Error Resume Next задает продолжение выполнения с инструкции, непосредственно следующей за инструкцией, которая привела к ошибке выполнения, или с инструкции, непосредственно следующей за вызывающей инструкцией в процедуре, содержащей конструкцию On Error Resume Next. Это позволяет продолжить исполнение программы несмотря на ошибку выполнения. Это позволяет также встроить подпрограмму обработки ошибок в процедуру, а не передавать управление в другую часть процедуры. Конструкция On Error Resume Next становится неактивной при вызове новой процедуры, поэтому для внутренней обработки ошибок необходимо выполнять инструкцию On Error Resume Next в каждой вызываемой процедуре.
При обработке ошибок, возникающих при доступе к другим объектам, рекомендуется использовать конструкцию On Error Resume Next, а не конструкцию On Error GoTo. Проверка объекта Err после каждого взаимодействия с другим объектом позволяет устранить неопределенность в том, при доступе к какому объекту возникла ошибка. Это позволяет всегда точно знать, какой объект поместил значение кода ошибки в свойство Err.Number, а также в каком объекте возникла ошибка (эта информация содержится в свойстве Err.Source).
Конструкция On Error GoTo 0 отключает обработку ошибок в текущей процедуре. Эта конструкция не задает переход на строку 0 для обработки ошибок, даже если в процедуре имеется строка с номером 0. Если инструкция On Error GoTo 0 не выполнялась, то обработчик автоматически отключается при выходе из процедуры.
Для того, чтобы предотвратить выполнение программы обработки ошибок в тех случаях, когда ошибка не возникла, следует помещать соответствующую инструкцию Exit Sub, Exit Function или Exit Property сразу после подпрограммы обработки ошибки, как в следующем примере:
Sub InitializeMatrix(Var1, Var2, Var3, Var4) On Error GoTo ОбработкаОшибок . . . Exit Sub ОбработкаОшибок: . . . Resume Next End Sub
В этом примере программа обработки ошибок помещена между инструкциями Exit Sub и End Sub, что позволяет отделить ее от части программы, соответствующей нормальному выполнению процедуры. Программу обработки ошибок можно разместить в любом месте процедуры.
Ошибки, которые не были перехвачены, возвращаются в управляющее приложение, если объект был запущен как исполняемый файл. В среде разработчика такие ошибки возвращаются в управляющее приложение только при указании соответствующих параметров. За описанием необходимых значений этих параметров и способов их задания следует обращаться к документации главного приложения. Там же следует проверить, позволяет ли главное приложение создавать классы.
Err.Number = vbObjectError + 1052
Системные ошибки при вызовах библиотек динамической компоновки (DLL) не приводят к возникновению исключений и не перехватываются средствами Visual Basic. При вызове функций из библиотек DLL необходимо проверять, успешно ли возвращается каждое значение (согласно спецификациям API), и в случае неудачи проверять значение свойства LastDLLError объекта Err.
Пример
В начале этой программы инструкция On Error GoTo определяет положение подпрограммы обработки ошибок в процедуре. В данном примере попытка удалить открытый файл приводит к возникновению ошибки с кодом 55. Ошибка обрабатывается в подпрограмме, после чего управление возвращается инструкции, которая привела к возникновению ошибки. Инструкция On Error GoTo 0 отключает перехват ошибок. После этого инструкция On Error Resume Next задает отложенный перехват ошибок, что позволяет точно определить, в каком контексте возникла ошибка, генерируемая в следующей инструкции. Следует отметить, что после обработки ошибки вызывается метод Err.Clear для сброса значений свойств объекта Err.
Sub OnErrorStatementDemo() On Error GoTo ErrorHandler ' Включаем программу обработки ' ошибок. Open "TESTFILE" For Output As #1 ' Открываем файл. Kill "TESTFILE" ' Попытка удалить открытый ' файл. On Error Goto 0 ' Отключаем перехват ошибок. On Error Resume Next ' Откладываем перехват ошибок. ObjectRef = GetObject("MyWord.Basic") ' Запускаем несуществующий ' объект, а затем проверяем ' ошибку механизма управления ' программируемыми объектами. If Err.Number = 440 Or Err.Number = 432 Then ' Выводим сообщение для пользователя и очищаем объект Err. Msg = "Ошибка при попытке открыть программируемый объект!" MsgBox Msg, , "Проверка отложенной ошибки" Err.Clear ' Очищаем поля объекта Err. End If Exit Sub ' Выходим из процедуры, чтобы ' не попасть в обработчик. ErrorHandler: ' Обработчик ошибок. Select Case Err.Number ' Определяем код ошибки. Case 55 ' "Ошибка "Файл уже открыт". Close #1 ' Закрываем открытый файл. Case Else ' Здесь размещаются инструкции для обработки других ошибок... End Select Resume ' Возобновляем выполнение ' со строки, вызвавшей ошибку. End Sub
На чтение 7 мин Просмотров 339 Опубликовано 16.12.2014
В этой статье мы рассмотри обработку ошибок в языке VBScript, а именно объектErr, конструкцию On Error Resume Next и On Error Goto 0. Конструкция VBScript On Error Resume Next включает обработку ошибок, а On Error Goto 0 отменяет их обработку.
Объект Err не нуждается в предварительном объявлении, и доступен всегда, давайте рассмотри его методы и свойства:
- Description — данное свойство содержит описание ошибки.
- Number — содержит целое число – номер ошибки. Если значение свойства Number ровно нулю – значит, ошибка отсутствует.
- Source — свойство содержит название приложения, в котором возникла ошибка.
Методы
Clear – полная очистка информации об ошибке. Стоит обратить внимание, что информация об ошибке автоматически очищается при выполнении операторов On Error Resume Next, Exit Sub и Exit Function.
Raise(number, [source, description]) – данный метод позволяет генерировать собственную ошибку времени выполнения. Видим, что тут можно задать параметры, аналогичные по своей принадлежности свойствам самого объекта Err. Видим, что тут является обязательным только первый параметр.
Хорошо, теперь давайте рассмотри четыре примера на языке vbscript.
Пример 1
'------------------------------------------------------------------------------' vbscript on error resume next' произойдет вычисление только для первых 3 значений' on_error_1.vbs'------------------------------------------------------------------------------ OptionExplicit 'включаем обработку ошибокOnErrorResumeNext dim MyArr(8), icount, Result, msgErr, msg ' заполняем массив MyArr(0) = 5 MyArr(1) = -3 MyArr(2) = 15 MyArr(3) = 0 MyArr(4) = 2 MyArr(5) = 6 MyArr(6) = 0 MyArr(7) = -1 icount=0msg=""msgErr = "Ошибка!!!" & vbCrLf 'циклично делим число 15 на каждый элемент массиваDo result=15/MyArr(icount) If Err.Number <> 0 ThenmsgErr=msgErr & "Код ошибки: " & Err.Number & vbCrLf &_ "Описание: " & Err.Description & vbCrLf &_ "Приложение: " & Err.Source & vbCrLf result = msgErr msgErr=""endif icount = icount+1 msg=msg & Result & vbCrLf & vbCrLfLoopWhile (icount <8) MsgBox msg
В данном примере мы создали массив из 8 элементов, каждый из которых является числом, два элемента – являются нулями. В цикле do…loop (работа данного цикла рассмотрена в статье Урок 7 по VBScript: Циклы do…loop и while…wend) идет деление числа 15 на каждый элемент массива (Урок 9 по VBScript: Массивы). Так как мы не включили в данном примере очистку информации об ошибке, то произойдёт деление только первых трёх значений, а всё остальное будет принято за ошибку.
Пример 2
'------------------------------------------------------------------------------' vbscript on error resume next' Вычисления не произойдут' on_error_2.vbs'------------------------------------------------------------------------------ OptionExplicit 'включаем обработку ошибокOnErrorResumeNext dim MyArr(8), icount, Result, msgErr, msg ' заполняем массив MyArr(0) = 5 MyArr(1) = -3 MyArr(2) = 15 MyArr(3) = 0 MyArr(4) = 2 MyArr(5) = 6 MyArr(6) = 0 MyArr(7) = -1 icount=0msg=""msgErr = "Ошибка!!!" & vbCrLf 'циклично делим число 15 на каждый элемент массиваDo result=15/MyArr(icount) If Err.Number <> 0 ThenmsgErr=msgErr + "Код ошибки: " & Err.Number & vbCrLf &_ "Описание: " & Err.Description & vbCrLf &_ "Приложение: " & Err.Source & vbCrLf result = msgErr msgErr=""' Отменяем обработку ошибок!!!OnErrorGoto 0 endif icount = icount+1 msg=msg & result & vbCrLf & vbCrLfLoopWhile (icount <8) MsgBox msg
Тут мы дополнительно использовали конструкцию On Error Goto 0, которая отключает обработку ошибок. Это приведёт к тому, что никакие вычисления не будут произведены, и при запуске сценария автоматически произойдёт ошибка времени выполнения.
Скачать архив с примерами
Пример 3
'------------------------------------------------------------------------------' on error resume next vbscript' Правильный подход обработки ошибок' on_error_3.vbs'------------------------------------------------------------------------------ OptionExplicit 'включаем обработку ошибокOnErrorResumeNext dim MyArr(8), icount, Result, msgErr, msg ' заполняем массив MyArr(0) = 5 MyArr(1) = -3 MyArr(2) = 15 MyArr(3) = 0 MyArr(4) = 2 MyArr(5) = 6 MyArr(6) = 0 MyArr(7) = -1 icount=0msg=""msgErr = "Ошибка!!!" & vbCrLf 'циклично делим число 15 на каждый элемент массиваDo'Очищаем информацию об ошибке Err.Clear result=15/MyArr(icount) If Err.Number <> 0 ThenmsgErr=msgErr + "Код ошибки: " & Err.Number & vbCrLf &_ "Описание: " & Err.Description & vbCrLf &_ "Приложение: " & Err.Source & vbCrLf result = msgErr msgErr=""endif icount = icount+1 msg=msg & result & vbCrLf & vbCrLfLoopWhile (icount <8) MsgBox msg
В этом примере мы сделали все правильно, так как вначале цикла прописали Err.Clear, который очищает информацию о предыдущих ошибках.
Ну и наконец четвертый пример, тут мы генерируем собственное описание ошибки.
Пример 4
'------------------------------------------------------------------------------' on error resume next vbscript' генерация собственной ошибки' on_error_4.vbs'------------------------------------------------------------------------------ OptionExplicit 'включаем обработку ошибокOnErrorResumeNext dim MyArr(8), icount, Result, msgErr, msg ' заполняем массив MyArr(0) = 5 MyArr(1) = -3 MyArr(2) = 15 MyArr(3) = 0 MyArr(4) = 2 MyArr(5) = 6 MyArr(6) = 0 MyArr(7) = -1 icount=0msg=""msgErr = "Ошибка!!!" & vbCrLf 'циклично делим число 15 на каждый элемент массиваDo'Очищаем информацию об ошибке Err.Clear result=15/MyArr(icount) If Err.Number <> 0 ThenErr.Raise 100, "текущий сценарий", "пробуем делить на ноль" msgErr=msgErr + "Код ошибки: " & Err.Number & vbCrLf &_ "Описание: " & Err.Description & vbCrLf &_ "Приложение: " & Err.Source & vbCrLf result = msgErr msgErr=""endif icount = icount+1 msg=msg & result & vbCrLf & vbCrLfLoopWhile (icount <8) MsgBox msg
Давайте подытожим сказанной в данной статье…. Должен сказать, что материал получился довольно сухим на предмет обзора, это и не удивительно — большую часть занимают примеры программного кода. В целом, мы рассмотрели внутренний объект Err, который содержит методы и свойства для обработки исключительных ситуаций в сценариях на языке VBSCRIPT.
“Abort, Retry, Fail?” – MS-DOS error message circa 1986
This post provides a complete guide to VBA Error Handing. If you are looking for a quick summary then check out the quick guide table in the first section.
If you are looking for a particular topic on VBA Error Handing then check out the table of contents below(if it’s not visible click on the post header).
If you are new to VBA Error Handling, then you can read the post from start to finish as it is laid out in logical order.
Contents
- 1 A Quick Guide to Error Handing
- 2 The Webinar
- 3 Download the Error Handling Library
- 4 Introduction
- 5 VBA Errors
- 5.1 Syntax Errors
- 5.2 Compilation Errors
- 5.2.1 Using Debug->Compile
- 5.2.2 Debug->Compile Error Summary
- 5.2.3 Debug->Compile Usage
- 5.3 Runtime Errors
- 5.3.1 Expected Versus Unexpected Errors
- 5.4 Runtime Errors that are not VBA Errors
- 6 The On Error Statement
- 6.1 On Error GoTo 0
- 6.2 On Error Resume Next
- 6.3 On Error GoTo [label]
- 6.4 On Error GoTo -1
- 6.5 Using On Error
- 7 Resume Next
- 8 The Err Object
- 8.1 Getting the Line Number
- 8.2 Using Err.Raise
- 8.3 Using Err.Clear
- 9 Logging
- 10 Other Error Related Items
- 10.1 Error Function
- 10.2 Error Statement
- 11 A Simple Error Handling Strategy
- 11.1 The Basic Implementation
- 12 A Complete Error Handling Strategy
- 12.1 An Example of using this strategy
- 13 Error Handling in a Nutshell
- 14 What’s Next?
A Quick Guide to Error Handing
Item | Description |
---|---|
On Error Goto 0 | When error occurs, the code stops and displays the error. |
On Error Goto -1 | Clears the current error setting and reverts to the default. |
On Error Resume Next | Ignores the error and continues on. |
On Error Goto [Label] | Goes to a specific label when an error occurs. This allows us to handle the error. |
Err Object | When an error occurs the error information is stored here. |
Err.Number | The number of the error. (Only useful if you need to check a specific error occurred.) |
Err.Description | Contains the error text. |
Err.Source | You can populate this when you use Err.Raise. |
Err.Raise | A function that allows you to generate your own error. |
Error Function | Returns the error text from an error number. Obsolete. |
Error Statement | Simulates an error. Use Err.Raise instead. |
The Webinar
Members of the Webinar Archives can access the webinar for this article by clicking on the image below.
(Note: Archive members have access to the webinar archive.)
Download the Error Handling Library
Introduction
Error Handling refers to code that is written to handle errors which occur when your application is running. These errors are normally caused by something outside your control like a missing file, database being unavailable, data being invalid etc.
If we think an error is likely to occur at some point, it is good practice to write specific code to handle the error if it occurs and deal with it.
For all other errors, we use generic code to deal with them. This is where the VBA error handling statement comes into play. They allow our application to deal gracefully with any errors we weren’t expecting.
To understand error handling we must first understand the different types of errors in VBA.
VBA Errors
There are three types of errors in VBA:
- Syntax
- Compilation
- Runtime
We use error handling to deal with runtime errors. Let’s have a look at each of these error types so that it is clear what a runtime error is.
Syntax Errors
If you have used VBA for any length of time you will have seen a syntax error. When you type a line and press return, VBA will evaluate the syntax and if it is not correct it will display an error message.
For example if you type If and forget the Then keyword, VBA will display the following error message
Some examples of syntax errors are
' then is missing If a > b ' equals is missing after i For i 2 To 7 ' missing right parenthesis b = left("ABCD",1
Syntax errors relate to one line only. They occur when the syntax of one line is incorrect.
Note: You can turn off the Syntax error dialog by going to Tools->Options and checking off “Auto Syntax Check”. The line will still appear red if there is an error but the dialog will not appear.
Compilation Errors
Compilation errors occur over more than one line. The syntax is correct on a single line but is incorrect when all the project code is taken into account.
Examples of compilation errors are:
- If statement without corresponding End If statement
- For without Next
- Select without End Select
- Calling a Sub or Function that does not exist
- Calling a Sub or Function with the wrong parameters
- Giving a Sub or Function the same name as a module
- Variables not declared(Option Explicit must be present at the top of the module)
The following screenshot shows a compilation error that occurs when a For loop has no matching Next statement.
Using Debug->Compile
To find compilation errors, we use Debug->Compile VBA Project from the Visual Basic menu.
When you select Debug->Compile, VBA displays the first error it comes across.
When this error is fixed, you can run Compile again and VBA will then find the next error.
Debug->Compile will also include syntax errors in it’s search which is very useful.
If there are no errors left and you run Debug->Compile , it may appear that nothing happened. However, “Compile” will be grayed out in the Debug menu. This means your application has no compilation errors at the current time.
Debug->Compile Error Summary
- Debug->Compile finds compilation(project wide) errors.
- It will also find syntax errors.
- It finds one error each time you use it.
- When there are no compilation errors left the Compile option will appear grayed out in the menu.
Debug->Compile Usage
You should always use Debug->Compile before you run your code. This ensures that your code has no compilation errors when you run it.
If you do not run Debug->Compile then VBA may find compile errors when it runs. These should not be confused with Runtime errors.
Runtime Errors
Runtime errors occur when your application is running. They are normally outside of your control but can be caused by errors in your code.
For example, imagine your application reads from an external workbook. If this file gets deleted then VBA will display an error when your code tries to open it.
Other examples of runtime errors are
- a database not being available
- the user entering invalid data
- a cell containing text instead of a number
As we have seen, the purpose of error handling is to deal with runtime errors when they occur.
Expected Versus Unexpected Errors
When we think a runtime error could occur we put code in place to handle it. For example, we would normally put code in place to deal with a file not being found.
The following code checks if the file exists before it tries to open it. If the file does not exist then a user friendly message is displayed and the code exits the sub.
' https://excelmacromastery.com/ Sub OpenFile() Dim sFile As String sFile = "C:docsdata.xlsx" ' Use Dir to check if file exists If Dir(sFile) = "" Then ' if file does not exist display message MsgBox "Could not find the file " & sFile Exit Sub End If ' Code will only reach here if file exists Workbooks.Open sFile End Sub
When we think an error is likely to occur at some point, it is good practice to add code to handle the situation. We normally refer to these errors as expected errors.
If we don’t have specific code to handle an error it is considered an unexpected error. We use the VBA error handling statements to handle the unexpected errors.
Runtime Errors that are not VBA Errors
Before we look at the VBA Handling there is one type of error we must mention. Some runtime errors are not considered errors by VBA but only by the user.
Let me explain this with an example. Imagine you have an application that requires you to add the values in the variables a and b
result = a + b
Let’s say you mistakenly use an asterisk instead of the plus sign
result = a * b
This is not a VBA error. Your code syntax is perfectly legal. However, from your requirements point of view it is an error.
These errors cannot be dealt with using error handling as they obviously won’t generate any error. You can deal with these errors using Unit Testing and Assertions. I have an in-depth post about using VBA assertions – see How to Make Your Code BulletProof.
The On Error Statement
As we have seen there are two ways to treat runtime errors
- Expected errors – write specific code to handle them.
- Unexpected errors – use VBA error handling statements to handle them.
The VBA On Error statement is used for error handling. This statement performs some action when an error occurs during runtime.
There are four different ways to use this statement
- On Error GoTo 0 – the code stops at the line with the error and displays a message.
- On Error Resume Next – the code moves to next line. No error message is displayed.
- On Error GoTo [label] – the code moves to a specific line or label. No error message is displayed. This is the one we use for error handling.
- On Error GoTo -1 – clears the current error.
Let’s look at each of these statements in turn.
On Error GoTo 0
This is the default behavior of VBA. In other words, if you don’t use On Error then this is the behavior you will see.
When an error occurs, VBA stops on the line with the error and displays the error message. The application requires user intervention with the code before it can continue. This could be fixing the error or restarting the application. In this scenario no error handling takes place.
Let’s look at an example. In the following code, we have not used any On Error line so VBA will use the On Error GoTo 0 behavior by default.
' https://excelmacromastery.com/ Sub UsingDefault() Dim x As Long, y As Long x = 6 y = 6 / 0 x = 7 End Sub
The second assignment line results in a divide by zero error. When we run this code we will get the error message shown in the screenshot below
When the error appears you can choose End or Debug
If you select End then the application simply stops.
If you select Debug the application stops on the error line as the screenshot below shows
This behaviour is fine when you are writing VBA code as it shows you the exact line with the error.
This behavior is unsuitable for an application that you are given to a user. These errors look unprofessional and they make the application look unstable.
An error like this is essentially the application crashing. The user cannot continue on without restarting the application. They may not use it at all until you fix the error for them.
By using On Error GoTo [label] we can give the user a more controlled error message. It also prevents the application stopping. We can get the application to perform in a predefined manner.
On Error Resume Next
Using On Error Resume Next tells VBA to ignore the error and continue on.
There are specific occasions when this is useful. Most of the time you should avoid using it.
If we add Resume Next to our example Sub then VBA will ignore the divide by zero error
' https://excelmacromastery.com/ Sub UsingResumeNext() On Error Resume Next Dim x As Long, y As Long x = 6 y = 6 / 0 x = 7 End Sub
It is not a good idea to do this. If you ignore the error, then the behavior can be unpredictable. The error can affect the application in multiple ways.You could end up with invalid data. The problem is that you aren’t aware that something went wrong because you have suppressed the error.
The code below is an example of where using Resume Next is valid
' https://excelmacromastery.com/ Sub SendMail() On Error Resume Next ' Requires Reference: ' Microsoft Outlook 15.0 Object Library Dim Outlook As Outlook.Application Set Outlook = New Outlook.Application If Outlook Is Nothing Then MsgBox "Cannot create Microsoft Outlook session." _ & " The email will not be sent." Exit Sub End If End Sub
In this code we are checking to see if Microsoft Outlook is available on a computer. All we want to know is if it is available or not. We are not interested in the specific error.
In the code above, we continue on if there is an error. Then in the next line we check the value of the Outlook variable. If there has been an error then the value of this variable will be set to Nothing.
This is an example of when Resume could be useful. The point is that even though we use Resume we are still checking for the error. The vast majority of the time you will not need to use Resume.
On Error GoTo [label]
This is how we use Error Handling in VBA. It is the equivalent of the Try and Catch functionality you see in languages such as C# and Java.
When an error occurs you send the error to a specific label. It is normally at the bottom of the sub.
Let’s apply this to the sub we have been using
' https://excelmacromastery.com/ Sub UsingGotoLine() On Error GoTo eh Dim x As Long, y As Long x = 6 y = 6 / 0 x = 7 Done: Exit Sub eh: MsgBox "The following error occurred: " & Err.Description End Sub
The screenshot below shows what happens when an error occurs
VBA jumps to the eh label because we specified this in the On Error Goto line.
Note 1: The label we use in the On…GoTo statement, must be in the current Sub/Function. If not you will get a compilation error.
Note 2: When an error occurs when using On Error GoTo [label], the error handling returns to the default behaviour i.e. The code will stop on the line with the error and display the error message. See the next section for more information about this.
On Error GoTo -1
This statement is different than the other three. It is used to clear the current error rather than setting a particular behaviour.
When an error occurs using On Error GoTo [label], the error handling behaviour returns to the default behaviour i.e. “On Error GoTo 0”. That means that if another error occurs the code will stop on the current line.
This behaviour only applies to the current sub. Once we exit the sub, the error will be cleared automatically.
Take a look at the code below. The first error will cause the code to jump to the eh label. The second error will stop on the line with the 1034 error.
' https://excelmacromastery.com/ Sub TwoErrors() On Error Goto eh ' generate "Type mismatch" error Error (13) Done: Exit Sub eh: ' generate "Application-defined" error Error (1034) End Sub
If we add further error handling it will not work as the error trap has not been cleared.
In the code below we have added the line
On Error Goto eh_other
after we catch the first error.
This has no effect as the error has not been cleared. In other words the code will stop on the line with the error and display the message.
' https://excelmacromastery.com/ Sub TwoErrors() On Error Goto eh ' generate "Type mismatch" error Error (13) Done: Exit Sub eh: On Error Goto eh_other ' generate "Application-defined" error Error (1034) Exit Sub eh_other: Debug.Print "eh_other " & Err.Description End Sub
To clear the error we use On Error GoTo -1. Think of it like setting a mouse trap. When the trap goes off you need to set it again.
In the code below we add this line and the second error will now cause the code to jump to the eh_other label
' https://excelmacromastery.com/ Sub TwoErrors() On Error Goto eh ' generate "Type mismatch" error Error (13) Done: Exit Sub eh: ' clear error On Error Goto -1 On Error Goto eh_other ' generate "Application-defined" error Error (1034) Exit Sub eh_other: Debug.Print "eh_other " & Err.Description End Sub
Note 1: There are probably rare cases where using On Error GoTo -1 is useful. In most cases using Resume Next is better as it clears the error and resumes the code at the next line after the error occurs.
Note 2: The Err Object has a member Clear. Using Clear clears the text and numbers in the Err object, but it does NOT reset the error.
Using On Error
As we have seen, VBA will do one of three things when an error occurs
- Stop and display the error.
- Ignore the error and continue on.
- Jump to a specific line.
VBA will always be set to one of these behaviors. When you use On Error, VBA will change to the behaviour you specify and forget about any previous behavior.
In the following Sub, VBA changes the error behaviour each time we use the On Error statement
' https://excelmacromastery.com/ Sub ErrorStates() Dim x As Long ' Go to eh label if error On Error Goto eh ' this will ignore the error on the following line On Error Resume Next x = 1 / 0 ' this will display an error message on the following line On Error Goto 0 x = 1 / 0 Done: Exit Sub eh: Debug.Print Err.Description End Sub
Resume Next
The Resume Next statement is used to clear the error and then resume the code from the line after where the error occurred.
If your code can have multiple errors and you want to keep detecting them then this line is very useful.
For example, in the following code we want to resume the code after the error has been reported:
Private Sub Main() On Error Goto eh Dim i As Long For i = 1 To 3 ' Generate type mismatch error Error 13 Next i done: Exit Sub eh: Debug.Print i, Err.Description End Sub
We could use On Error Goto -1 to clear the code and then use a goto statement to go back to the code like this:
Private Sub Main() On Error Goto eh Dim i As Long For i = 1 To 3 ' Generate type mismatch error Error 13 continue: Next i done: Exit Sub eh: Debug.Print i, Err.Description On Error Goto -1 ' clear the error Goto continue ' return to the code End Sub
The Resume Next provides a nicer way of doing it and it always means the code is much clearer and easier to understand:
Private Sub Main() On Error Goto eh Dim i As Long For i = 1 To 3 ' Generate type mismatch error Error 13 continue: Next i done: Exit Sub eh: Debug.Print i, Err.Description ' clear the error and return to the code Resume Next End Sub
The Err Object
When an error occurs you can view details of the error using the Err object.
When an runtime error occurs, VBA automatically fills the Err object with details.
The code below will print “Error Number: 13 Type Mismatch” which occurs when we try to place a string value in the long integer total
' https://excelmacromastery.com/ Sub UsingErr() On Error Goto eh Dim total As Long total = "aa" Done: Exit Sub eh: Debug.Print "Error number: " & Err.Number _ & " " & Err.Description End Sub
The Err.Description provides details of the error that occurs. This is the text you normally see when an error occurs e.g. “Type Mismatch”
The Err.Number is the ID number of the error e.g. the error number for “Type Mismatch” is 13. The only time you really need this is if you are checking that a specific error occurred and this is only necessary on rare occasions.
The Err.Source property seems like a great idea but it does not work for a VBA error. The source will return the project name, which hardly narrows down where the error occurred. However, if you create an error using Err.Raise you can set the source yourself and this can be very useful.
Getting the Line Number
The Erl function is used to return the line number where the error occurs.
It often causes confusion. In the following code, Erl will return zero
' https://excelmacromastery.com/ Sub UsingErr() On Error Goto eh Dim val As Long val = "aa" Done: Exit Sub eh: Debug.Print Erl End Sub
This is because there are no line numbers present. Most people don’t realise it but VBA allows you to have line numbers.
If we change the Sub above to have line number it will now print out 20
' https://excelmacromastery.com/ Sub UsingErr() 10 On Error Goto eh Dim val As Long 20 val = "aa" Done: 30 Exit Sub eh: 40 Debug.Print Erl End Sub
Adding line numbers to your code manually is cumbersome. However there are tools available that will allow you to easily add and remove line numbers to a sub.
When you are finished working on a project and hand it over to the user it can be useful to add line numbers at this point. If you use the error handling strategy in the last section of this post, then VBA will report the line where the error occurred.
Using Err.Raise
Err.Raise allows us to create errors. We can use it to create custom errors for our application which is very useful. It is the equivalent of the Throw statement in JavaC#.
The format is as follows
Err.Raise [error number], [error source], [error description]
Let’s look at a simple example. Imagine we want to ensure that a cell has an entry that has a length of 5 characters. We could have a specific message for this
' https://excelmacromastery.com/ Public Const ERROR_INVALID_DATA As Long = vbObjectError + 513 Sub ReadWorksheet() On Error Goto eh If Len(Sheet1.Range("A1")) <> 5 Then Err.Raise ERROR_INVALID_DATA, "ReadWorksheet" _ , "The value in the cell A1 must have exactly 5 characters." End If ' continue on if cell has valid data Dim id As String id = Sheet1.Range("A1") Done: Exit Sub eh: ' Err.Raise will send code to here MsgBox "Error found: " & Err.Description End Sub
When we create an error using Err.Raise we need to give it a number. We can use any number from 513 to 65535 for our error. We must use vbObjectError with the number e.g.
Err.Raise vbObjectError + 513
Using Err.Clear
Err.Clear is used to clear the text and numbers from the Err.Object. In other words, it clears the description and number.If you want the clear the actual error you can use either On Error GoTo -1 or Resume Next
It is rare that you will need to use Err.Clear but let’s have a look at an example where you might.
In the code below we are counting the number of errors that will occur. To keep it simple we are generating an error for each odd number.
We check the error number each time we go through the loop. If the number does not equal zero then an error has occurred. Once we count the error we need to set the error number back to zero so it is ready to check for the next error.
' https://excelmacromastery.com/ Sub UsingErrClear() Dim count As Long, i As Long ' Continue if error as we will check the error number On Error Resume Next For i = 0 To 9 ' generate error for every second one If i Mod 2 = 0 Then Error (13) ' Check for error If Err.Number <> 0 Then count = count + 1 Err.Clear ' Clear Err once it is counted End If Next Debug.Print "The number of errors was: " & count End Sub
Note 1: Err.Clear resets the text and numbers in the error object but it does not clear the error – see Resume Next Or On Error GoTo -1 for more information about clearing the actual error.
Logging
Logging means writing information from your application when it is running. When an error occurs you can write the details to a text file so you have a record of the error.
The code below shows a very simple logging procedure
' https://excelmacromastery.com/ Sub Logger(sType As String, sSource As String, sDetails As String) Dim sFilename As String sFilename = "C:templogging.txt" ' Archive file at certain size If FileLen(sFilename) > 20000 Then FileCopy sFilename _ , Replace(sFilename, ".txt", Format(Now, "ddmmyyyy hhmmss.txt")) Kill sFilename End If ' Open the file to write Dim filenumber As Variant filenumber = FreeFile Open sFilename For Append As #filenumber Print #filenumber, CStr(Now) & "," & sType & "," & sSource _ & "," & sDetails & "," & Application.UserName Close #filenumber End Sub
You can use it like this
' Create unique error number ' https://excelmacromastery.com/ Public Const ERROR_DATA_MISSING As Long = vbObjectError + 514 Sub CreateReport() On Error Goto eh If Sheet1.Range("A1") = "" Then Err.Raise ERROR_DATA_MISSING, "CreateReport", "Data is missing from Cell A1" End If ' other code here Done: Exit Sub eh: Logger "Error", Err.Source, Err.Description End Sub
The log is not only for recording errors. You can record other information as the application runs. When an error occurs you can then check the sequence of events before an error occurred.
Below is an example of logging. How you implement logging really depends on the nature of the application and how useful it will be:
' https://excelmacromastery.com/ Sub ReadingData() Logger "Information", "ReadingData()", "Starting to read data." Dim coll As New Collection ' add data to the collection coll.Add "Apple" coll.Add "Pear" If coll.Count < 3 Then Logger "Warning", "ReadingData()", "Number of data items is low." End If Logger "Information", "ReadingData()", "Number of data items is " & coll.Count Logger "Information", "ReadingData()", "Finished reading data." End Sub
Having a lot of information when dealing with an error can be very useful. Often the user may not give you accurate information about the error that occurred. By looking at the log you can get more accurate information about the information.
This section covers some of the other Error Handling tools that VBA has. These items are considered obsolete but I have included them as they may exist in legacy code.
Error Function
The Error Function is used to print the error description from a given error number. It is included in VBA for backward compatibility and is not needed because you can use the Err.Description instead.
Below are some examples:
' Print the text "Division by zero" Debug.Print Error(11) ' Print the text "Type mismatch" Debug.Print Error(13) ' Print the text "File not found" Debug.Print Error(53)
Error Statement
The Error statement allows you to simulate an error. It is included in VBA for backward compatibility. You should use Err.Raise instead.
In the following code we simulate a “Divide by zero” error.
' https://excelmacromastery.com/ Sub SimDivError() On Error Goto eh ' This will create a division by zero error Error 11 Exit Sub eh: Debug.Print Err.Number, Err.Description End Sub
This statement is included in VBA for backward compatibility. You should use Err.Raise instead.
A Simple Error Handling Strategy
With all the different options you may be confused about how to use error handling in VBA. In this section, I’m going to show you how to implement a simple error handling strategy that you can use in all your applications.
The Basic Implementation
This is a simple overview of our strategy
- Place the On Error GoTo Label line at the start of our topmost sub.
- Place the error handling Label at the end of our topmost sub.
- If an expected error occurs then handle it and continue.
- If the application cannot continue then use Err.Raise to jump to the error handling label.
- If an unexpected error occurs the code will automatically jump to the error handling label.
The following image shows an overview of how this looks
The following code shows a simple implementation of this strategy:
' https://excelmacromastery.com/ Public Const ERROR_NO_ACCOUNTS As Long = vbObjectError + 514 Sub BuildReport() On Error Goto eh ' If error in ReadAccounts then jump to error ReadAccounts ' Do something with the code Done: Exit Sub eh: ' All errors will jump to here MsgBox Err.Source & ": The following error occured " & Err.Description End Sub Sub ReadAccounts() ' EXPECTED ERROR - Can be handled by the code ' Application can handle A1 being zero If Sheet1.Range("A1") = 0 Then Sheet1.Range("A1") = 1 End If ' EXPECTED ERROR - cannot be handled by the code ' Application cannot continue if no accounts workbook If Dir("C:DocsAccount.xlsx") = "" Then Err.Raise ERROR_NO_ACCOUNTS, "UsingErr" _ , "There are no accounts present for this month." End If ' UNEXPECTED ERROR - cannot be handled by the code ' If cell B3 contains text we will get a type mismatch error Dim total As Long total = Sheet1.Range("B3") ' continue on and read accounts End Sub
This is a nice way of implementing error handling because
- We don’t need to add error handling code to every sub.
- If an error occurs then VBA exits the application gracefully.
A Complete Error Handling Strategy
The above strategy has one major drawback. It doesn’t provide any information about the error. It is better than having no strategy as it prevents the application crashing. But that is the only real benefit.
VBA doesn’t fill Err.Source with anything useful so we have to do this ourselves.
In this section, I am going to introduce a more complete error strategy. I have written two subs that perform all the heavy lifting so all you have to do is add them to your project.
The purpose of this strategy is to provide you with the Stack* and line number when an error exists.
*The Stack is the list of sub/functions that were currently in use when the error occurred.
This is our strategy
- Place error handling in all the subs.
- When an error occurs, the error handler adds details to the error and raises it again.
- When the error reaches the topmost sub it is displayed.
We are simply “bubbling” the error to the top. The following diagram shows a simple visual of what happens when an error occurs in Sub3
The only messy part to this is formatting the strings correctly. I have written two subs that handle this, so it is taken care of for you.
There are the two helper subs, RaiseError and DisplayError. You can download the library below:
An Example of using this strategy
Here is a simple coding example that uses these subs. In this strategy, we don’t place any code in the topmost sub. We only call subs from it.
' https://excelmacromastery.com/ Sub Topmost() On Error Goto EH Level1 Done: Exit Sub EH: DisplayError Err.source, Err.Description, "Module1.Topmost", Erl End Sub Sub Level1() On Error Goto EH Level2 Done: Exit Sub EH: RaiseError Err.Number, Err.source, "Module1.Level1", Err.Description, Erl End Sub Sub Level2() On Error Goto EH ' Error here Dim a As Long a = "7 / 0" Done: Exit Sub EH: RaiseError Err.Number, Err.source, "Module1.Level2", Err.Description, Erl End Sub
The result looks like this:
If your project has line numbers the result will include the line number of the error:
Error Handling in a Nutshell
- Error Handling is used to handle errors that occur when your application is running.
- You write specific code to handle expected errors. You use the VBA error handling statement On Error GoTo [label] to send VBA to a label when an unexpected error occurs.
- You can get details of the error from Err.Description.
- You can create your own error using Err.Raise.
- Using one On Error statement in the top most sub will catch all errors in subs that are called from here.
- If you want to record the name of the Sub with the error, you can update the error and rethrow it.
- You can use a log to record information about the application as it is running.
What’s Next?
Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.
Related Training: Get full access to the Excel VBA training webinars and all the tutorials.
(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)