Обработка ошибок в 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.
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
VBA On Error Statements
VBA On Error is an easy method for handling unexpected exceptions in Excel Macros.It is known that we cannot write code without any error. Sometimes writing big code may give us an error even at the time of compiling. To avoid this kind of situation, we add an Error Message which, instead of giving us the right answer or error code it will show us the message with the error code. That would look like we got the output of our calculation, but it is the error code that will get imprinted.
How to Use Excel VBA On Error Statements in Excel?
There are 3 ways of Error in VBA. Let’s understand different ways with some examples.
Example #1
The first error type is a Code compilation error which comes when a code is undeclared or impossible variables. To understand more, we will use a simple mathematical expression of the divide. For this, go to the Insert menu of VBA and select Module as shown below.
Now open Subcategory and add any name as we are using On Error, so we have named it as same.
Sub OnError() End Sub
Now define any 2 or 3 Integers. Here we have taking X and Y as Integers.
Sub OnError() Dim X As Integer, Y As Integer, Z As Integer End Sub
Now, as discussed above, we will calculate division mathematical expression. For X, we will put a character in Numerator and divide it 0. And Y will be 20/2, which is complete numbers.
Sub OnError() Dim X As Integer, Y As Integer X = Test / 0 Y = 20 / 2 End Sub
Now run the code by using the F5 key or clicking on the play button as shown below. We will get Run-time error 6, which shows Text over number error.
Now to overrule this error, we will add one line On Error Resume Next before we write the mathematical code. It will jump the error code, but we will not able to see the outcome of the second mathematical code. This only hides the error message of various codes lines, as shown below. Now try to run the code as well.
Sub OnError() Dim X As Integer, Y As Integer On Error Resume Next X = Test / 0 Y = 20 / 2 MsgBox X MsgBox Y End Sub
Now to overrule this error, we will add one line On Error Resume Next before we write the mathematical code. It will jump the error code, but we will not able to see the outcome of the second mathematical code. This only hides the error message of various codes lines, as shown below. Now try to run the code as well.
Example #2
In this example, we will consider that mathematical division which gives infinite result, but in coding, it will #DIV/0 result. To demonstrate this, we will consider one more integer Z along with X and Y in a subcategory, as shown below.
Sub OnError() Dim X As Integer, Y As Integer, Z As Integer End Sub
Now frame all the integers X, Y, and Z with a mathematical expression of divide and to print it use MsgBox function in VBA of each integer’s result.
Below for Integer X, we have divided 10 by 0, 20 by 2 and 30 by 4.
Sub OnError() Dim X As Integer, Y As Integer, Z As Integer X = 10 / 0 Y = 20 / 2 Z = 30 / 4 MsgBox X MsgBox Y MsgBox Z End Sub
Now run the code using the F5 key or manually, as shown below.
As we can see in the above screenshot, Run-time error 11, which means the error is related to the number. Now to overcome this, add one line On Error Resume Next before mathematical expression as shown below.
Sub OnError() Dim X As Integer, Y As Integer, Z As Integer On Error Resume Next X = 10 / 0 Y = 20 / 2 Z = 30 / 4 MsgBox X MsgBox Y MsgBox Z End Sub
Now, if we run the code, we will get zero for the first integer X and for Y and Z, we will get respective division answers as shown below.
Example #3
The second type of error is seen when we enter incorrect data entry in code. For this, we will consider 3 integers, X, Y, and Z, by opening the Subcategory in VBA as shown below.
Sub OnError() Dim X As Integer, Y As Integer, Z As Integer End Sub
Now also consider the same mathematical division which we have seen in the above example.
Sub OnError() Dim X As Integer, Y As Integer, Z As Integer X = 10 / 0 Y = 20 / 2 Z = 30 / 4 MsgBox X MsgBox Y MsgBox Z End Sub
If we run the code, we will get the same error message of Run-time error 11.
Now to overrule this error, use text On Error GoTo with the word “ “Result to skip the error message and get the output which works fine, as shown below.
Sub OnError() Dim X As Integer, Y As Integer, Z As Integer On Error GoTo ZResult: X = 10 / 0 Y = 20 / 2 ZResult: Z = 30 / 4 MsgBox X MsgBox Y MsgBox Z End Sub
Now run the code again. We will get the same result as the previous example.
On Error GoTo ZResult helps us to directly jump of mentioned result point integer as we did for integer Z.
Example #4
In the third type of error, when we run the code and VBA is not able to understand the line of code. This can be done with the help of code On Error Resume Next along with MsgBox Err.Number. Consider the same data as used in the above examples. We will again see the same 3 integers X, Y, and Z, as shown below.
Sub OnError() Dim X As Integer, Y As Integer, Z As Integer End Sub
And for printing the result output, allow message boxes for all Integers as output.
Sub OnError() Dim X As Integer, Y As Integer, Z As Integer X = 10 / 0 Y = 20 / 2 Z = 30 / 4 MsgBox X MsgBox Y MsgBox Z End Sub
Now, if we run the complete code, then we will get an error message of mathematical error Run time error 11.
Now to overrule this error, we will use On Error Resume Next.
Sub OnError() Dim X As Integer, Y As Integer, Z As Integer On Error Resume Next X = 10 / 0 Y = 20 / 2 Z = 30 / 4 MsgBox X MsgBox Y MsgBox Z End Sub
And run the code. This will give a use result on a valid mathematical line, as shown below.
Now further add ZResult code line before Z integer division mathematical expression and add MsgBox Err.Number code line at the end of code as shown below.
Sub OnError() Dim X As Integer, Y As Integer, Z As Integer On Error Resume Next X = 10 / 0 Y = 20 / 2 ZResult: Z = 30 / 4 MsgBox X MsgBox Y MsgBox Z MsgBox Err.Number End Sub
Now run the code by using the F5 key or by pressing the play button, as shown below.
As we can see in the above screenshots. The first message box has 0, which is overruling of incorrect mathematical expression. 2nd and 3rd have a division result of Y and Z integers. And last message box has run time error code 11, which is probably the error code of X integer’s division expressions.
Pros of VBA On Error
- We can calculate any mathematical formula even if it is incorrect.
- For bigger coding structures where there are chances of having an error, using these methods may give correct result even among the line of codes.
- This gives a better result as compared to the result obtained from normal excel calculations.
Things to Remember
- Always save the file in a Macro-Enabled Excel file so that we can use created VBA code many and multiple times.
- Always compile the written code before implementing with any excel requirement.
- If needed, assign the written code to any button so that we can quickly click on the button and run the code.
You can download this VBA On Error Excel Template here – VBA On Error Excel Template.
Recommended Articles
This has been a guide to Excel VBA On Error. Here we discussed how to use VBA On Error Statement along with some practical examples and a downloadable excel template. You can also go through our other suggested articles–
- VBA TRIM
- VBA Number Format
- VBA Do While Loop
- VBA Find
If VBA can’t execute a statement (command) then a run-time error occurs. By default Excel deals with these, so when a run-time error occurs, you’ll see a default error message like this:
But you can change this and instruct Excel to allow your code to deal with run-time errors.
NOTE : I’m going to use the terms sub, function and procedure interchangeably. For the purposes of this article they all mean the same thing – a chunk of code written to do a particular thing.
The On Error Statement
To instruct Excel what to do when an error occurs, you use the On Error statement. You can use On Error in four ways:
On Error GoTo 0 On Error Resume Next On Error GoTo [label] On Error GoTo -1
On Error GoTo 0
This is the default mode and is already turned on when you start writing your code. You don’t need to use an On Error GoTo 0 statement at the start of your VBA.
In this mode VBA displays the standard style error message box, and gives you the choice to Debug the code (enter VBA editor and use debugging tools) or End code execution.
You would use On Error GoTo 0 to turn default error handling back on if you have previously told VBA to deal with errors in some other way e.g. by using On Error Resume Next.
On Error Resume Next
On Error Resume Next tells VBA to continue executing statements immediately after the statement that generated the error.
On Error Resume Next allows your code to continue running even if an error occurs. Resume Next does not fix an error, it just ignores it. This can be good and bad.
The Good?
If you know that your code could generate an error, then using Resume Next can prevent an interruption in code execution.
For example, we want to create a file, but I want to make sure a file with the same name doesn’t already exist. To do this, I will attempt to delete the file, and of course if it doesn’t already exist, an error will occur.
I don’t care if an error occurs. If it does, the file doesn’t exist and that’s fine for what I want to do. So before I attempt to delete the file, I instruct VBA to ignore the error.
Sub DeleteFile() Dim FilePath As String FilePath = "d:tempsomefile.csv" On Error Resume Next 'Delete the file Kill FilePath 'If the file doesn't exist the Kill statement 'generates an error. 'But I have assumed that is ok as it indicates that 'I am ok to create a new file with the same filename 'This is a bad assumption - see the next sub 'UnhandledError() End Sub
The Bad
But hang on. What if the file I am trying to delete is read only? If it is I will get an error when I try to delete it. I’ve assumed that I will only get an error if the file isn’t there. So an error caused by trying to delete a read only file will get missed.
And If I then try to create a new file with the same name, or open it for writing data to it, I will generate more errors and they will be missed too.
Sub UnhandledError() Dim FilePath As String FilePath = "d:tempsomefile.csv" On Error Resume Next 'Delete the file Kill FilePath 'But if the file is read-only I can't delete it 'and the Kill statement generates an error 'I can't now create a new file with the same name 'Trying to Open the file for writing data to it will 'also generate an error but it will be missed as 'we've told VBA to continue executing code if an 'error occurs Open FilePath For Output As #1 Write #1, "Some data" Close #1 End Sub
If you do use On Error Resume Next you should immediately turn default error handling back on (or turn on your custom error handler – see below)
Be careful when using On Error Resume Next. You are better off seeing if an error occurred by checking the Err object (see below). Doing this can tell you the error number and help you figure out exactly what happened.
On Error GoTo [LABEL]
If an error occurs, this transfers code execution to the line following the label. This is typically used to specify your own error handling code.
None of the code between the line generating the error and the label is executed.
Error Handlers
So you write your own error handling code and use On Error GoTo [LABEL] to instruct VBA to use your code to deal with errors.
You can place your error-handling code anywhere in a procedure, but typically it is placed at the end.
Your error handler should either fix the error and resume code execution, or terminate the routine gracefully.
Sub ErrorHandler() Dim num As Integer On Error GoTo ErrHandler num = 1 / 0 MsgBox "This line is not executed" Exit sub ErrHandler: MsgBox "Oops, an error has occured." & vbCrLf & vbCrLf & "Error Code : " & Err.Number & " , " & Err.Description End Sub
As VBA will execute each line of code in turn going from top to bottom, if no error is generated then it will execute your error handling code when it gets to that point in your sub.
To prevent this happening, use an Exit Sub, Exit Function, or Exit Property statement before your error handling routine.
In the example above, if the value assigned to num was valid e.g. num = 1/1, then we don’t want the code beneath ErrHandler: executed. So just before the ErrHandler: label, I’ve used an Exit Sub statement.
Multiple Error Handlers
You can have more than one error handler in a routine, but only one of them can be active at any time.
You could have something like:
Sub MultipleErrorHandlers() On Error GoTo ErrHandler1 [some code] On Error GoTo ErrHandler2 [some code] Exit Sub ErrHandler1: [ErrHandler1 Code] Exit Sub ErrHandler2: [ErrHandler1 Code] Exit Sub End Sub
If an error occurs between On Error GoTo ErrHandler1 and On Error GoTo ErrHandler2 then the ErrHandler1 code is executed.
If an error occurs after On Error GoTo ErrHandler2 then the ErrHandler2 code is executed.
NOTE: Notice that at the end of each error handling routine is an Exit Sub statement. If I didn’t use these, when the ErrHandler1 code is finished executing, VBA could just continue on down to the next line and execute the ErrHandler2 code as well.
Strictly speaking I don’t need the Exit Sub at the end of the ErrHandler2 code, as it is the last line in the sub, but it is a good habit to get into.
Err object
When an error occurs the Err object contains information about the error like the error number and a description of the error.
As any given line of code can generate multiple errors it’s a good idea to examine the Err object to determine what you want to do in your code.
Err.Number gives you the error number, and Err.Description gives you a description of the error.
Sub CheckErrObject() Dim FilePath As String FilePath = "d:tempsomefile.csv" On Error GoTo ErrHandler 'Delete the file Kill FilePath Open FilePath For Output As #1 Write #1, "Some data" Close #1 Exit Sub ErrHandler: Select Case Err.Number Case 53 ' File doesn't exist Err.Clear ' Clear the error Case 75 ' File is Read Only MsgBox "Error Number : " & Err.Number & vbCrLf & vbCrLf & Err.Description Exit Sub Case Else ' Code to handle other errors End Select Resume Next ' Continue executing code after line that generated error End Sub
Resume
The Resume statement tells VBA to resume executing code at a specified point. Resume can only be used in an error handling routine, any other use will generate an error.
Resume takes three forms:
Resume Resume Next Resume [label]
Using just Resume causes execution to resume at the same line of code that caused the error. If you haven’t fixed the error, your code will begin an infinite loop as it switches between the line of code generating the error and the error handling routine.
If you look at the example sub Resume_Next() which is below, num = 1 / 0 causes a Divide by 0 error. I’ve instructed VBA to use my error handler, called ErrHandler.
In ErrHandler I’ve attempted to fix the error by assigning num the value 1. If I then used only Resume, all that would happen is that VBA would go back to num = 1 / 0 and another Divide by 0 error would be generated.
Instead, I use Resume Next to carry on executing code at the line after the one causing the error.
In doing so I have handled the error by assigning the value 1 to num, and execution will continue without another error at the line result = num / 1
Sub Resume_Next() Dim num As Integer Dim result As Integer On Error GoTo ErrHandler num = 1 / 0 result = num / 1 Exit Sub ErrHandler: num = 1 Resume Next End Sub
Resume [label] passes code execution to the line with that label.
Sub Resume_Next() Dim num As Integer Dim result As Integer On Error GoTo ErrHandler num = 1 / 0 result = num / 1 MyLabel: ‘Code execution starts again from here result = num * 1 Exit Sub ErrHandler: num = 1 Resume MyLabel End Sub
Whenever you use Resume it clears the Err object.
Error Handling With Multiple Procedures
Every sub/function doesn’t have to have an error handler. If an error occurs, VBA will use the last On Error statement to determine what happens.
If an On Error statement has been used in a procedure and an error occurs in that procedure, then that error is handled as I’ve just described.
But if an error occurs in a sub that hasn’t used an On Error statement, VBA goes back through procedure calls until it finds an On Error directive.
Let’s look at an example with three subs.
SubOne() calls SubTwo(). SubTwo calls SubThree(), and has some code of its own to execute. SubThree() carries out a calculation.
Sub SubOne() On Error GoTo ErrHandler SubTwo Exit Sub ErrHandler: MsgBox "Error caught in SubOne" End Sub Sub SubTwo() SubThree MsgBox "No errors here" End Sub Sub SubThree() Dim num As Integer num = 1 / 0 End Sub
SubOne() has an error handler routine, ErrHandler, and has instructed VBA to use it.
SubTwo() will display a message on screen after it’s call to SubThree() has finished.
However SubThree() generates a Divide by 0 error.
SubThree() hasn’t used an On Error statement to tell VBA what to do if an error occurs, so VBA goes back to SubTwo(). That also doesn’t have an On Error statement so VBA goes back to SubOne().
Here we have our error handler and the code in it is executed.
Note that the message «No errors here» in SubTwo() is not displayed because that line of code is not executed.
When SubThree() generated an error, code execution went back to the error handler in SubOne() and any code in SubTwo() after the call to SubThree() is missed out.
On Error GoTo -1
This resets the current error. It’s the equivalent of using Err.Clear.
You can see that in this sub, after the Divide By 0 error is generated, after On Error GoTo -1 is used, Err.Number is 0 (no error) and Err.Description is empty.
Sub GoToMinus1() Dim num As Integer On Error Resume Next num = 1 / 0 'If error is Divide by Zero If Err.Number = 11 Then MsgBox "Error Code : " & Err.Number & " , " & Err.Description On Error GoTo -1 MsgBox "Error Code : " & Err.Number & " , " & Err.Description End If End Sub
Sample Code
Enter your email address below to download the sample workbook.
By submitting your email address you agree that we can email you our Excel newsletter.
Содержание
- Оператор On Error
- Синтаксис
- Примечания
- Пример
- См. также
- Поддержка и обратная связь
- VBA On Error – Error Handling Best Practices
- VBA Errors Cheat Sheet
- Errors
- VBA Error Handling
- VBA On Error Statement
- On Error GoTo 0
- On Error Resume Next
- VBA Coding Made Easy
- 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 Code Examples Add-in
Оператор On Error
Включает программу обработки ошибок и указывает местоположение этой программы в процедуре; также может использоваться для отключения программы обработки ошибок.
Синтаксис
On Error GoTo line
On Error Resume Next
On Error GoTo 0
Синтаксис оператора On Error может принимать любую из следующих форм:
Statement | Описание |
---|---|
On Error GoTo line | Включает процедуру обработки ошибок, которая начинается в строке, указанной в аргументе обязательной строки .
Аргумент line представляет собой любую метку строки или любой номер строки. Если возникает ошибка во время запуска, управление ветвями для строки, что делает обработник ошибок активным. Указанная строка должна быть в той же процедуре, что и оператор On Error; в противном случае происходит ошибка во время компиляции. |
On Error Resume Next | Указывает, что при ошибке во время выполнения управление переходит к заявлению сразу после утверждения, где произошла ошибка, и выполнение продолжается. Используйте эту форму вместо On Error GoTo при доступе к объектам. |
On Error GoTo 0 | Отключает любой включенный обработчик ошибок в текущей процедуре. |
Примечания
Если оператор On Error не используется, любая случившаяся ошибка выполнения является неустранимой; то есть в этом случае отображается сообщение об ошибке и выполнение прекращается.
«Включенный» обработчик ошибок — это обработчик, включенный оператором On Error; «активный» обработчик — это включенный обработчик, который находится в процессе обработки ошибки. Если ошибка возникает при активном обработнике ошибок (между возникновением ошибки и резюме, выходом из подгруппы , функцией exit или exit Property ), обработник ошибки текущей процедуры не может справиться с ошибкой. Управление возвращается к вызывающей процедуре.
Если вызывающая процедура содержит включенный обработчик ошибок, он активируется для обработки ошибки. Если обработчик ошибок вызывающей процедуры также активный, управление передается обратно через предыдущие вызывающие процедуры до тех пор, пока не будет найден включенный, но неактивный обработчик. Если не удается найти неактивный включенный обработчик ошибок, ошибка является неустранимой в той точке, в которой она фактически произошла.
Каждый раз, когда обработчик ошибок передает управление обратно вызывающей процедуре, эта процедура становится текущей процедурой. После обработки ошибки обработчивем ошибки в любой процедуре, выполнение возобновляется в текущей процедуре в точке, указанной в заявлении Resume .
Процедура обработки ошибок не является процедурой Sub или Функцией . Это раздел кода, помеченный меткой строки или номером строки.
Процедуры обработки ошибок зависят от значения в свойстве Номер объекта 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 непосредственно перед программой обработки ошибок, как показано в следующем фрагменте:
Здесь код обработки ошибок следует заявлению Exit Sub и предшествует заявлению End Sub , чтобы отделить его от потока процедуры. Код обработки ошибок может помещаться в любом месте процедуры.
Неперехваченные ошибки в объектах возвращаются в управляющее приложение, когда объект выполняется как исполняемый файл. В среде разработки неперехваченные ошибки только возвращаются в управляющее приложение, если заданы надлежащие параметры. Следующие сведения см. в документации ведущего приложения: какие параметры следует задать во время отладки, как задать эти параметры, может ли ведущее приложение создавать классы.
Если создается объект, имеющий доступ к другим объектам, следует попытаться обработать ошибки, передаваемые из этих объектов необработанными. Если вам не удается обрабатывать такие ошибки, сопоставьте код ошибки в Err.Number с одной из собственных ошибок и затем передайте их обратно вызывающей стороне объекта. Следует указать ошибку, добавив код ошибки в константу vbObjectError. Например, если код вашей ошибки — 1052, назначьте его следующим образом:
Системные ошибки во время вызовов Windows динамических библиотек ссылок (DLL) или ресурсов кода Macintosh не вызывают исключений и не могут быть заблокированы с помощью Visual Basic ошибок. При вызове функций DLL необходимо проверить каждое возвращаемого значения на успешность или сбой (в соответствии со спецификациями API), а в случае сбоя проверьте значение в свойстве lastDLLError объекта Err. Свойство LastDLLError всегда возвращает ноль в Macintosh.
Пример
В этом примере сначала используется оператор On Error GoTo для указания местоположения программы обработки ошибок в процедуре. В примере попытка удалить открытый файл генерирует ошибку номер 55. Ошибка обрабатывается в программе обработки ошибок, и затем управление возвращается к оператору, вызвавшему ошибку. Оператор On Error GoTo 0 выключает перехват ошибок.
Затем заявление On Error Resume Next используется для отсрочки улавливания ошибок, чтобы можно было точно знать контекст ошибки, порожденной следующим утверждением. Обратите внимание, что Err.Clear используется для очистки свойств объекта Err после обработки ошибки.
См. также
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
VBA On Error – Error Handling Best Practices
In this Article
VBA Errors Cheat Sheet
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 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:
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):
On Error Resume Next
On Error Resume Next tells VBA to skip any lines of code containing errors and proceed to the next line.
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.
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!
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’.
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.
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):
and create a line label like this:
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 do this by placing the error handler line label at the end of your procedure:
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:
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:
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.
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:
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.
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.
VBA Ignore Error
To ignore errors in VBA, simply use the On Error Resume Next statement:
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:
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:
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.
VBA Error Handling in Access
All of the above examples work exactly the same in Access VBA as in Excel VBA.
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
While writing Excel Macros we generally put more focus on the coding part and getting the desired result but during this process, we forget an important thing i.e. Error handling. Error handling is an important part of every code and VBA On Error Statement is an easy way for handling unexpected exceptions in Excel Macros.
A well-written macro is one that includes proper exception handling routines to catch and tackle every possible error. Error handling is important because in case of any unexpected exceptions your code doesn’t break. Even if any fatal unexpected error occurs in the code then also you should ensure that the code should terminate gracefully.
Definition of VBA On Error Statement:
On Error statement instructs VBA Compiler, what to do in case any runtime exception is thrown.
Syntax of On Error Statement:
Basically, there are three types of On Error statement:
- On Error Goto 0
- On Error Resume Next
- On Error Goto<label>:
On Error Goto 0
This is also called VBA default exception handling. When On Error Goto 0 is in effect, it is the same as having no error handler in the code. Here we are instructing the program to display the standard runtime message box with ‘Continue’, ‘End’, ‘Debug’, and ‘Help’ buttons.
This message box will give you four options:
a. Continue: This will ignore the exception and continue the code, only if it is possible to do so.
b. End: This will terminate the program.
c. Debug: This option will bring the program control back to the statement from where the exception has occurred. This helps you to debug the code.
d. Help: This button will open Microsoft MSDN help pages for that exception.
On Error Resume Next
It is the second form of the On Error statement. This statement tells the VBA program to ignore the error and resume the execution with the next line of code.
On Error Resume Next statement doesn’t fix the runtime errors but it simply means that program execution will continue from the line following the line that caused the error. However, it is the sole responsibility of the programmer to make sure that any handled error should not have any side effects (like uninitialized variables or null objects) on the program execution.
This can be ensured by using the VBA Err object. Err object in VBA comes into the picture whenever any runtime error occurs. The Err object preserves information about one exception at a time. When an exception occurs, the Err object is updated to include information about that exception.
For instance:
For example, I have a simple macro as follows:
Sub GetErr()
On Error Resume Next
N = 1 / 0 ' Line causing divide by zero exception
For i = 1 To N
'SomeSet of Statements
Next i
End Sub
Now as you can clearly see, that in this macro Line 3 causes an exception. But as we are using the On Error Resume Next statement so this line will be skipped and the control will flow to the next statement. But the next statement is a loop that is dependent on the value of ‘N’, and at this step ‘N’ is uninitialized so this will have a side effect on the whole flow of the program.
Now, have a look at the same program after exception handling:
Sub GetErr()
On Error Resume Next
N = 1 / 0 ' Line causing divide by zero exception
If Err.Number <> 0 Then
N = 2 ' Some minimum value of N if there is some exception in the code.
End If
For i = 1 To N
'SomeSet of Statements
Next i
End Sub
Now, here in this code, we are checking the Err. Number property, if it is not equal to zero that means there is some exception in the code. And hence we have set ‘N’ to its minimum value so that there are no side effects in the code due to uninitialized variables.
On Error Goto<label>:
This is the third form in which VBA On Error statement can be used. This statement tells the VBA to transfer the program control to the line followed by the label, in case any runtime errors are encountered. In such cases, all the statements between the exception line and the label will not be executed.
This method is more suitable for exiting the program gracefully if any fatal error occurs during the execution.
Example:
Below is a self-explanatory example of ‘On Error Goto<label>:’ where I have used the label name as ‘Error_handler’.
Sub GetErr()
On Error GoToError_handler:
N = 1 / 0 ' cause an error
MsgBox "This line will not be executed"
Exit Sub
Error_handler:
MsgBox "exception handler"
End Sub
In this code as soon as the exception occurs at Line 3, the program transfers the control to Line 6.
Notice that here I have used ‘Exit Sub’ just before the ‘Error_handler:’ label, this is done to ensure that the Error handler block of code doesn’t execute if there is no error. If you omit the ‘Exit Sub’ statement then the Error handler code block will always execute even if no exception is encountered.
So, this was all about the On Error statement in Excel VBA.