Vba excel on error exit

Обработка ошибок в VBA Excel с помощью оператора On Error. Синтаксис выражений с оператором On Error. Пример кода с простым обработчиком ошибок.

Обработка ошибок в 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.

Home / VBA / VBA Exit Sub Statement

VBA Exit Sub is a statement that you use to exit a sub-procedure or a function. As you know, each line is a macro executes one after another, and when you add the “Exit Sub” VBA, exit the procedure without running the rest of the code that comes after that. It works best with loops and the message box.

Using Exit Sub Statement in VBA

  1. First, decide on which line you want to add the “Exit Sub”.
  2. After that, check the structure of the code that will get executed when you run the code.
  3. Next, enter the “Exit Sub”.
  4. In the end, it’s better to have comment that describes why you are using the “Exit Sub” statement.

Note: In a VBA function procedure, the statement that you need to use is “Exit Function”.

Use Exit Sub with a Message Box and Input Box

Let’s say you want to get input from the user with an input box and exit the procedure if the user’s reply is not a number (consider the following example).

In the above code, you have ISNUMERIC that checks for the value entered in the input box if it’s a number or not, and if that value is not a number, it uses the Exit Sub statement to end the procedure after showing a message box.

Sub vba_exit_sub_example()

If IsNumeric(InputBox("Enter your age.", "Age")) = False Then
    MsgBox "Error! Enter your Age in numbers only."
    Exit Sub
Else
    MsgBox "Thanks for the input."
End If

End Sub

On Error Exit Sub

One of the best things about the “Exit Sub” you can use it to exit the procedure when an error occurs. Below is the code that divides a number with a zero that returns a “Run-time error ‘11’ “ and stops the execution.

Here you can use the GoTo statement to create an error handler with the “Exit Sub” to exit the procedure (consider the following code).

Sub vba_exit_sub_on_error()

On Error GoTo iError
Range("A1") = 10 / 0

iError:
MsgBox "You can't divide with the zero." & _
"Change the code."
Exit Sub

End Sub

In the above code, you have an error handler, “iError” with a message box and then the “Exit Sub” Statement. When an error occurs during the calculation, the goto statement jumps to the error handler (VBA Error Handling), and it will exit the procedure.

Активизирует подпрограмму обработки ошибок и указывает положение подпрограммы в процедуре; используется также для отключения подпрограммы обработки ошибок.

  • 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

Excel VBA Errors & Error Handling, On Error & Resume Satements, Exit Statement, Err Object

————————————————————————————————-

Contents:

VBA Erros & Error Handling

Error Handling Setting, in VBE

Error Handler

On Error Statements

Using an Exit Statement

Error Handling in Nested Procedures & The Resume Statement

Get Information from the Error Object

Raise Method of the Err Object: Generate a Run-time error

————————————————————————————————-

Error Handling determines what is to be done next on the occurrence of an error. On encountering a run-time error, an On Error statement enables or disables an error-handling routine within a procedure. A Resume statement can only be used in an error-handling routine — it resumes execution at a sepcified point after the error-handline routine finishes. You can get information on the error from the properties of the Error object — this object is the Err Object. In this section, we cover:

VBA Erros & Error Handling

In vba programming you can have Syntax Errors or Run-time Errors. An error handler determines what action is to be taken within a procedure, on the occurrence of a run-time error.

A syntax error occurs when you enter a line of code which is not allowed or recognized by Visual Basic. You will encounter a syntax error on misspelling a keyword or a named argument, for incorrect punctuation (ex. not specifying a comma as a placeholder for the omitted argument), use an undefined procedure, and so on. These errors are easier to locate as the Code Editor points them out at the time you are writing your code.

A run-time error occurs at the time during which your code is running, that is after you have created your macro. There could be an error in your programming due to incorrect logic used in your code that prevents it from doing what you intended and may stop code execution, for example, if your code attempts to divide a value by zero. Another reason for an error which may cause even a valid code to crash could be a condition not being met, say, a reference to a worksheet in your code which has been deleted by the user. Other examples when a run-time error can occur are: on using incorrect variable names or variable types; if your code goes into an infinite loop; using a value or reference outside the allowable range; and so on. If you dont implement error handling in your macro, on encountering a run-time error your code will stop execution and go into Break Mode and display an error message, thereby confusing and frustrating the user.

Using Error Handling in VBA is an important tool for developers to trap & handle run-time errors in a vba procedure for seamless execution. It is important to set error handling in every procedure else your macro might just crash or stop executing on encountering a run-time error and vba will display a default error message and go into Break Mode allowing the user to debug your code.

Basic Error Handling hides the fault in the macro when it crashes and exits gracefully, and informs the users accordingly. Advanced Error Handling techniques involve saving information on the error cause and the point of the error, and attempt to resolve the error and provide information to the user on the next step.

Error Handling determines what is to be done next on the occurrence of an error. At a basic level, Error Handling involves two parts — (i) enables an error-handling routine with an On Error Statement on encountering an error, and (ii) an error-handling routine which is the section where the procedure flow is directed to on encountering an error. It is to be noted that an error-handling routine is not a procedure (Sub or Function) but a section of code marked by a line label or a line number. An On Error statement enables or disables an error-handling routine within a procedure.

Error Handling Setting, in VBE

You can determine how errors are handled in VBE, by selecting the appropriate option. In VBE, click Options on the Tools Menu, select the General tab in the dialog box. In the Error Trapping Section, you can select from 3 options.

Break on All Errors: Selecting this will stop your code execution and enter Break Mode on every error, even if you are using an error handler (including the On Error Resume Next statement), hence it is not advised to select this option.

Break on Unhandled Errors: This works well in that an error is trapped when an error handler is active else the error causes the macro to go into Break Mode, except for debugging class modules wherein on encountering an error the debugger stops on the line which calls the class and not on the actual error line in the class, thus making it difficult to spot the error and fixing it.

Break in Class Module: Selecting this option will cause an unhandled error in a class module to stop code execution and go into Break Mode at the actual error causing line of code in that class module, but does not work if you use raise errors in your classes via the Err.Raise command which will actually cause an “error”.

Error Handler

An error handler determines what action is to be taken within a procedure, on the occurrence of an error. An ‘enabled’ error handler is the one which is enabled by the On Error Statement; an ‘active’ error handler is the ‘enabled’ error handler which is in the process of handling an error. On encountering an error you may decide to exit the procedure, or else you may want to rectify the error and resume execution. For this you will use On Error statements or Resume statements. A Resume statement can only be used in an error-handling routine — it resumes execution after the error-handline routine finishes.

On Error Statements

On encountering a run-time error, an On Error statement enables or disables an error-handling routine within a procedure. If an error-handling routine is enabled, procedure flow is directed to the error-handling routine which handles the error.

On Error GoTo line

The On Error GoTo line Statement enables the error-handling routine, which is the section starting at the line specified in the line argument. The line argument is required to be specified, and it can be any line label or line number in the same procedure as the On Error statement. A compile-time error will occur if the specified line argument is not in the same procedure as as the On Error statement. The On Error GoTo statement traps all errors, without exceptions.

On Error Resume Next

This Statement specifies that on the occurrence of a run-time error, the procedure flow is directed to the next statement which follows the statement where the error occurred. This effectively skips the error and continues with the macro execution.

An On Error Resume Next statement becomes inactive on calling another procedure is called, hence it needs to be specified in every procedure that is called to use this error handling therein. Note that the properties of the Error object (Err Object) get cleared automatically when Resume Next is used in an error-handling routine, but not on using the Resume Next statement otherwise. Using the On Error Resume Next statement only defers error trapping & handling, whereas an error-handling routine handles the error and using the Resume Next statement therein resumes execution at same line that caused the error.

On Error GoTo 0

On Error GoTo 0 statement Disables any enabled error handler in the current procedure — it means as having no error handler in the code. This statement does not specify 0 as the start of the error-handling routine even though a line numbered 0 may be present in the procedure. An error handler is automatically disabled when a procedure is exited or if it has has run completely, if the procedure does not have an On Error GoTo 0 statement.

Using an Exit Statement

Placing an Exit Sub, Exit Function or Exit Property statement

For a procedure containing an error-handling routine, you will also need to include an exit routine within the procedure to ensure that the error-handling routine runs only if an error is encountered. This can be done by placing an Exit Sub, Exit Function or Exit Property statement immediately above the error-handling routine, if you don’t want it to execute when there is no error.

Single Exit Point

It may be preferable, not necessary, to have a single exit point in your procedure, so that after the Error Handler has handled the error, the procedure flow is directed to a point within the procedure so that the procedure exit is the same under all circumstances. This can be done by placing a Resume statement — Resume <Label> — the Label determines the point at which procedure flow is resumed after the Error Handler has handled the error. This Label has no effect on code execution if no error has occurred. It is preferable to have a single exit point because usually some type of clean up is required before the procedure exits, ex. you often enter Application.EnableEvents = False at the beginning of the code  for a worksheet_change event and because EnableEvents is not automatically changed back to True you add Application.EnableEvents = True at the end of the code before exit. A single exit point will obviate the need to duplicate this clean up code in the error-handling routine.

Error Handling in Nested Procedures & The Resume Statement

Using a Resume Statement

A Resume statement can only be used in an error-handling routine — it resumes execution at a sepcified point after the error-handline routine finishes. You can aslo exit or end the procedure after the error-handling routine finishes and not necessarily use the Resume statement. We discuss below three types of syntax used for the Resume statement, and how the control transfers (ie. code execution resumes) by these Resume statements. You should always use a Resume statement instead of a GoTo statement within an error-handling routine, because using a «GoTo line» statement apparantly deactivates subsequent Error Handling — even though both Resume & GoTo statements direct procedure flow out of the error-handling routine.

Resume or Resume 0: Where the error occurrs in the same procedure as the error handler, control is returned to the statement that caused the error and execution resumes at this line. Where the error occurrs in a called procedure, control is returned to the last calling statement in the procedure containing the error handler.

Resume Next: Where the error occurrs in the same procedure as the error handler, control is returned to  the next statement which follows the statement that caused the error and execution resumes at this line. Where the error occurrs in a called procedure, control is returned to the next statement which follows the last calling statement in the procedure containing the error handler.

Resume line: When an error occurrs in a procedure, control transfers to the line specified in the line argument. The line argument is a line label or line number and should be in the same procedure as the error handler.

Which Resume Statement to use:

The Resume or Resume 0 statement is used when it is necessary for the macro to correct the error and re-execute the corrected code — say when the user enters an invalid value and you want to prompt the user to enter a valid value and resume at the same line and re-excecute. The Resume Next statement is used when the error handler corrects the error and it is not required to re-execute the error code but to continue execution at the next line. The Resume line statement is used when you want to continue execution at another point in the procedure, which could also be an exit routine.

Given below are 2 Examples which illustrate using On Error Statements & Error Handler in a Procedure

Example 1: 

Sub OnErrorResNxtSt()
‘using an On Error Resume Next Statement in a procedure for handling errors
‘a run-time error 1004 occurs while naming another sheet with the same name

‘execution flows to the next statement which follows the statement that caused the error

On Error Resume Next

Dim strNewName As String, ws As Worksheet, response As Integer

‘add a new worksheet at the end

ActiveWorkbook.Worksheets.Add After:=Worksheets(Sheets.Count)

WsName:

‘enter name for worksheet

strNewName = InputBox(«Enter Worksheet Name»)

‘StrPtr — String Pointer — function used to determine if Cancel button has been pressed.

If StrPtr(strNewName) = 0 Then

MsgBox «You have pressed Cancel, Exiting Procedure without changing Worksheet Name»

Exit Sub

End If

‘rename the new worksheet — if name already exists, a run-time error 1004 will occur

ActiveSheet.Name = strNewName

‘Check Err object Number property if it corresponds to the error no. 1004.

‘Error No. 1004 occurs if worksheet with the same name already exists

If Err = 1004 Then

response = MsgBox(«Name already Exists, do you want to retry?», vbYesNo + vbQuestion)

If response = vbYes Then

‘clear error

Err.Clear

‘if worksheet name already exists, enter a new name

GoTo WsName

Else

MsgBox «Exiting Procedure without changing Worksheet Name»

Exit Sub

End If

End If

‘returns 0 — either no error occurred or error was cleared

MsgBox Err.Number

End Sub

Example 2: 

Sub OnErrorGoToSt()
‘using an On Error GoTo Statement in a procedure for handling errors, and a Resume statement within an error-handling routine
‘a run-time error 1004 occurs while naming another sheet with the same name

On Error GoTo ErrHandler

Dim strNewName As String, ws As Worksheet

‘add a new worksheet at the end

ActiveWorkbook.Worksheets.Add After:=Worksheets(Sheets.Count)

WsName:

‘enter name for worksheet

strNewName = InputBox(«Enter Worksheet Name«)

‘StrPtr — String Pointer — function used to determine if Cancel button has been pressed.

If StrPtr(strNewName) = 0 Then

MsgBox «You have pressed Cancel, Exiting Procedure»

GoTo exit_proc

End If

‘rename the new worksheet — if name already exists, a run-time error 1004 will occur

ActiveSheet.Name = strNewName

‘returns 0 — either no error occurred or error was cleared (using Resume statement in an error-handling routine, automatically clears the error)

MsgBox Err.Number

‘exit routine to skip error handler

exit_proc:

Exit Sub

ErrHandler:

‘Error No. 1004 occurs in this case if worksheet with the same name already exists

If Err = 1004 Then

MsgBox «Name already exists»

‘resumes execution at this point (WsName)

Resume WsName

Else

‘resumes execution at exit routine and exits sub

Resume exit_proc

End If

End Sub

Error Handling in a Called Procedure

If the called procedure in which an error has occurred does not have an error handler, VBA searches backward in the calling procedures for an enabled error handler, and if found the control is transferred to that error handler in the calling procedure. If an enabled error handler is not found in the backward search, then execution will stop in the current procedure displaying an error message.

Example 3:  Error in Nested Procedures — in the absence of an error handler in the called procedure in which an error has occurred, VBA searches backward in the calling procedures and control is transferred to an enabled error handler, if present, in the calling procedure.

Sub CallMarksGrades()
‘this is the calling procedure, with an error handler and Resume statements — the error handler is capable of correcting Type Mismatch, Overflow & Division by Zero errors.

On Error GoTo ErrHandler

‘Declare constants to indicate likely errors

Dim iMarks As Integer, iTotalMarks As Integer, dPcnt As Double, response As Integer

Const conErrorTypeMismatch As Long = 13

Const conErrorDivZero As Long = 11

Const conErrorOverflow As Long = 6

M:

iMarks = InputBox(«Enter Marks«)

TM:

iTotalMarks = InputBox(«Enter Total Marks«)

‘call the MarksPercent function and the result is assgined to the local variable dPcnt

dPcnt = MarksPercent(iMarks, iTotalMarks)

MsgBox «Percentage is » & dPcnt & «%»

‘exit routine to skip error handler

exit_proc:

Exit Sub

ErrHandler:

MsgBox Err

‘Check Err object Number property if it corresponds to the Type Mismatch error

‘a Type Mismatch error will occur if you have entered a non-numerical or pressed Cancel in the Input Box

If Err = conErrorTypeMismatch Then

response = MsgBox(«You may have entered a non-numerical value or pressed Cancel, do you want to Exit procedure?», vbYesNo + vbQuestion)

If response = vbYes Then

Resume exit_proc

Else

‘after correcting the error, resume execution at the same line which caused the error ie. Input Box is re-generated for making a valid entry

Resume

End If

‘Check Err object Number property if it corresponds to the Overflow error (where values exceed limitations or allowable range)

ElseIf Err = conErrorOverflow Then

MsgBox «Overflow error — also possible if both Marks & Total Marks are zero»

‘after correcting an Overflow error, resume execution at the specified line ie. M, which generates the Input Boxes afresh

Resume M

‘Check Err object Number property if it corresponds to the Division by Zero error

ElseIf Err = conErrorDivZero Then

MsgBox «Division by Zero error — Total Marks cannot be zero»

‘after correcting a division by zero error, resume execution at the specified line ie. TM, which generates the Input Box for iTotalMarks

Resume TM

Else

‘control is returned to  the next statement which follows the statement that caused the error

Resume Next

End If

End Sub

Function MarksPercent(Marks As Integer, TotalMarks As Integer) As Double
‘this is the called procedure — in case of an error in this procedure, say a division by zero run-time error no. 11,  VBA searches backward in the calling procedures for an enabled error handler, and if found the control is transferred  to that error handler in the calling procedure.

MarksPercent = Marks / TotalMarks * 100

MarksPercent = Round(MarksPercent, 2)

End Function

If an error occurs in a called procedure within an active error handler which does not correct for that error, using the Raise method to regenerate the original error will force Visual Basic to search backward through the calling procedures hierarchy for an enabled error handler. The Err object’s Raise method is useful to regenerate an original error in a vba procedure — refer the section on Error Object for details on the Raise Method. This is useful in cases where the called procedure’s error handler is not equipped to correct the error either because this type of error was not expected to occur in the called procedure or for any other reason. In this scenario the sequence will be that an error occurrs in a called procedure — the called procedure has an enabled error handler which does not correct the error, and the original error is regenerated using the Raise Method — Visual Basic is forced to do a backward search and execution flows to the error handler (if present) of the immediately preceding calling procedure, which may or may not correct the error — if the immediately preceding calling procedure does not have an error handler or its error handler is not capable of correcting the error and the error is regenerated then the backward search continues. If you do not regenerate the error in the called procedure whose enabled error handler is incapable of handling the error, the error may cause the macro to stop or continue with the error causing other errors.

Example 4:  Error in Nested Procedures — for an error in a called procedure with an active error handler which does not correct for that error, on Regenerating the error with the Raise Method, VBA searches backward in the calling procedures and control is transferred to an enabled error handler, if present, in the calling procedure.

Sub Calling_Proc()
‘calling procedure — this handles any error, and corrects in case it is a File Not Found error no. 53

Const conFileNotFound As Integer = 53

On Error GoTo ErrHandler

‘call another procedure

Call Called_Proc

‘exit routine to skip error handler

exit_routine:

Exit Sub

‘error handling routine of the calling procedure

ErrHandler:

‘error is corrected if it is a File Not Found error no. 53

If Err = conFileNotFound Then

MsgBox «Error No 53 — File Not Found, will create a New File to Copy»

Dim strFileToCopy As String, strFileCopied As String

strFileToCopy = «Book11.xlsx«

strFileCopied = «Book22.xlsx«

‘create a new workbook:

Workbooks.Add

‘save as .xlsx file, the default Excel 2007 file format, using the FileFormat Enumeration xlOpenXMLWorkbook (value 51):

ActiveWorkbook.SaveAs fileName:=strFileToCopy, FileFormat:=xlOpenXMLWorkbook

‘close workbook after saving changes:

ActiveWorkbook.Close SaveChanges:=True

‘this will copy the file

FileCopy strFileToCopy, strFileCopied

MsgBox «File Created & Copied»

‘if error is other than a File Not Found error no. 53

Else

MsgBox «Unresolved Error, Exiting Procedure»

End If

‘resumes execution at exit routine and exits sub

Resume exit_routine

End Sub

Sub Called_Proc()
‘this is a called procedure with an error handler that will correct only a Path not found error no. 76
‘for any other error in this procedure, say if the file is not found in the path/directory, the Raise method is used to regenerate the original error and execution flows to an enabled error handler (if present) in the calling procedure

‘Declare constant to indicate anticipated error

Const conPathNotFound As Integer = 76

Dim strFilePath As String, intOrigErrNum As Integer

Dim strFileToCopy As String, strFileCopied As String

strFileToCopy = «Book11.xlsx«

strFileCopied = «Book22.xlsx«

On Error GoTo ErrHandler76

‘specify file path: PATH NOT FOUND ERROR OCCURS HERE

‘not finding the specified path will give a run-time error ’76’ — Path not found

strFilePath = «C:ExcelFiles«

ChDir strFilePath

‘OTHER ERROR OCCURS HERE

‘attempting to Copy a file which does not exist will give a run-time error ’53’ — File not found

FileCopy strFileToCopy, strFileCopied

MsgBox «File Copied»

‘exit routine to skip error handler

exit_proc:

Exit Sub

ErrHandler76:

‘Check Err object Number property if it corresponds to the Path not found error.

If Err = conPathNotFound Then

‘correcting the Path in the Error Handler

strFilePath = ThisWorkbook.Path

MsgBox «Correcting Error No 76 — Path changed to ThisWorkbook path»

‘after correcting the Path, resume execution at the same line which caused the error

Resume

Else

‘for an error other than error no. 76, determine error number.

intOrigErrNum = Err.Number

‘clear error

Err.Clear

MsgBox «Error is other than error no. 76 — will Search Backward in Calling Procedures for an Error Handler to correct this error»

‘Regenerate original error — this will search backward in the calling procedures for an Error Handler if its exists

Err.Raise intOrigErrNum

‘resumes execution at exit routine and exits sub — execution flows to an enabled error handler in the calling procedure if it exists

Resume exit_proc

End If

End Sub

Get Information from the Error Object

Err Object & Properties: On the occurrence of a run-time error, you can get information on the error from the properties of the Error object (this object is the Err Object), which will help you in managing the error and to determine what is to be done next. The Number Property (Err.Number) returns a numeric value specifying the error with a value of zero meaning no error — this is the error’s number. The Number Property is the default property of the Err object. The Description Property (Err.Description) returns a short description of the error but this may not exist at times — if no Visual Basic error corresponds to the Number property, the «Application-defined or object-defined error» message is used. The Description property returns a zero-length string («») if no run-time error has occurred or ErrorNumber is 0. The property settings of the Err object relate to the most recent run-time error, so it is important that your error-handling routine saves these values before the occurrence of another error.

Use the Clear Method (Err.Clear) to to explicitly clear all property settings of the Err object. Using an Exit Sub, Exit Function or Exit Property statement, or using Resume Next statement in an error-handling routine, automatically calls the Clear Method and resets the numeric properties (viz. Number property) of the Err object to zero and the string properties (viz. Description property) to zero-length strings («»). However, the properties of the Err object are not reset when you use any Resume statement outside of an error-handling routine. Err.Clear is used to clear the properties of the Err object properties after the error is handled — using the On Error Resume Next statement defers error handling, whereas an error-handling routine handles the error and using the Resume Next statement therein resumes execution at same line that caused the error. Note that setting the error number to zero (Err.Number = 0) is not the same as using the Clear method because this does not reset the description property.

Using the Source property (Err.Source) lets you know what generated the error — Source returns the name of the object or application that generated the error. Source contains the project name for an error in a standard module. Source is the programmatic ID of your application if an error is generated by your application from code. Source contains a name with the project.class form, for an error in a class module. Source can be specifically defined by the user while using the Raise Method to generate an error. This property may not be very useful in providing information on vba run-time erros as it basically returns the name of the project in which the error occurred.

For Error Handling within a procedure it is usual to programmatically use only the Number property of the Err object, while other properties of the Err object are useful to provide additional information to the user on the cause of the error. Many times in your code it may be preferable to use the On Error Resume Next statement over On Error GoTo statement, because by checking the Err object’s properties after each interaction with an object (line of code) you can determine which object or statement originally generated what error — refer Example 1.

Example 5: Illustrating some common run-time errors in vba, with their respective Error.Number & Error.Description

Sub RunTimeErrorsInVba()
‘Illustrating some common run-time errors in vba, with their respective Error.Number & Error.Description
‘Err.Source in all cases below is «VBAProject», except in 2 instances of Run-time error ‘1004’ wherein the Source is «Microsoft Office Excel»

‘Run-time error ’11’: Division by zero (dividing a number by zero will give this error)

MsgBox 2 / 0

‘Run-time error ‘9’: Subscript out of range (This error occurs if you attempt to access array elements & members of collections beyond their defined ranges. In this case Sheet does not exist — active Workbook contains only 3 sheets)

MsgBox Sheets(7).Name

‘Run-time error ‘1004’: Application-defined or object-defined error (invalid reference). Err.Source returns ‘VBAProject’

Cells(1, 1).Offset(-1, 0) = 5

‘Run-time error ‘1004’: Select method of Range class failed (Sheet1 is not the active sheet whereas Select Method is valid for active sheet only). Err.Source returns ‘Microsoft Office Excel’

Sheets(«Sheet1»).Cells(1, 1).Select

‘Run-time error ‘1004’: Cannot rename a sheet to the same name as another sheet, a referenced object library or a workbook referenced by Visual Basic (renaming the active sheet wherein sheet with the same name already exists).

Err.Source returns ‘Microsoft Office Excel’

ActiveSheet.Name = «Sheet1«

‘Run-time error ’76’: Path not found (the specified path is not found)

ChDir «C:ExcelClients»

‘Run-time error ’68’: Device unavailable (drive does not exist)

ChDrive «H»

‘run-time error ’53’ — File not found (copy or delete a file which does not exist viz. Book1.xlsx)

FileCopy ActiveWorkbook.Path & «» & «Book1.xlsx», ActiveWorkbook.Path & «» & «Book2.xlsx»

Kill ActiveWorkbook.Path & «» & «Book1.xlsx»

‘Run-time error ’91’: Object variable or With block variable not set (using an object variable that does not yet reference a valid object: an error is generated on the reference to ws because the Set statement is omitted viz. Set ws =

ActiveSheet)

Dim ws As Worksheet

ws = ActiveSheet

MsgBox ws.Name

‘Run-time error ‘424’: Object required (sheet name is not a valid object)

Dim ws As Worksheet

Set ws = ActiveSheet.Name

‘Run-time error ’13’: Type mismatch (variable is of incorrect type — reference is to a range object & not worksheet — variable should be declared as — Dim ws As Range)

Dim ws As Worksheet

Set ws = ActiveSheet.Cells(1, 1)

‘entering a string value in the input box below will give a Run-time error ’13’: Type mismatch

Dim result As Single

result = InputBox(«Enter a number»)

‘Run-time error ‘6’: Overflow (this error occurs if you attempt to assign values exceeding the assigned target’s limit — in the present case the value of i is larger than an integer because an integer can hold whole numbers in the range -32,768

to 32,767)

Dim i As Integer

i = 100 * 20000

MsgBox i

End Sub

Raise Method of the Err Object: Generate a Run-time error

Raise Method is used to generate a run-time error. You can raise either a pre-defined error using its corresponding error number, or generate a custom (user-defined) error. Though Raise can be used in place of the Error statement, but because errors generated by using the Error statement give richer information in the Err object, Raise is useful to generate run-time errors for system errors and class modules. Syntax: Err.Raise(Number, Source, Description, HelpFile, HelpContext). The Raise method generates a specific error and the Err object properties are populated with information on that error. Only the Number argument is necessary to specify in the Raise Method, and all other arguments are optional. If optional arguments are omitted and the Err object properties contain uncleared values, those values are assumed for your error values. The Err object’s Raise method is useful to regenerate an original error in a vba procedure — if an error occurs within an active error handler which does not correct for that error, using the Raise method to regenerate the original error will force Visual Basic to search backward through the calling procedures for an enabled error handler. This has been explained & illustrated in Example 4 above.

Arguments of Raise Method: The Number argument is the error’s number. The Source argument represents the source of the error. The Description argument describes the error providing additional information about it. The HelpFile and HelpContext arguments represent the help file and help context ID used to link help to the error message box.

Raise Custom Errors (user-defined errors) using the Err Object’s Raise Method:

You can deliberately generate custom (run-time) errors in vba code, using the Raise Method of the Err Object. You may want to generate a custom error when your code does something you don’t want, for example, to prevent a user from inputting data which may be outside an acceptable range, you can stop the macro by raising an error, complete with an error code and the source of occurrence. To enable this, use the Err object’s Raise method.

The arguments of the Raise Method correspond to the properties of the Err object, and all arguments except the Number argument are optional. While raising a custom error you can set your own custom arguments in the Raise Method. You can raise pre-defined errors using their respective error numbers, but for a custom error you cannot use an error number which is in conflict with any Office built-in error number. To set Err.Number for your custom error, add the number you select as an error code to the vbObjectError constant (-2147221504) to ensure your custom error number is not in conflict with any built-in error numbers, for ex. to return the number -2147220504 as an error code, assign vbObjectError + 1000 to the Err.Number property — Err.Raise vbObjectError + 1000. One option is to set the Source argument as the name of the procedure in which the error occurs.

Example 6: Raise a custom error using Raise Method of the Err object, if length of name is less than 4 characters

Sub RaiseCustomError_1()
‘raise a custom error using Raise Method of the Err object, if length of name is less than 4 characters

   
On Error GoTo CustomError_Err

Dim strName As String

strName = «Jo«

If Len(strName) < 4 Then

‘an error occurs if name length < 4 characters — raise a custom error

Err.Raise Number:=vbObjectError + 1000, Description:=»Minimum Length of Name is 4 characters«

Else

‘macro executes if no error

MsgBox «Name: » & strName

End If

    
‘if no error, display message is «Program Executed»

MsgBox «Program Executed»

CustomError_End:

Exit Sub

    
CustomError_Err:

‘Display error number and description in message box: «Error Number: -2147220504, Description: Minimum Length of Name is 4 characters»

MsgBox «Error Number: » & Err.Number & «, Description: » & Err.Description

‘display message is «Exit Program without Executing»

MsgBox «Exit Program without Executing»

‘resume execution at this point after error handler has handled an error

Resume CustomError_End

End Sub

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.

VBA On Error

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:

  1. On Error Goto 0
  2. On Error Resume Next
  3. 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.

Standard-Runtime-Error-Msgbox

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.

Excel VBA Exit Sub Procedure

Exit Sub statement exits the sub procedure earlier than the defined lines of VBA codes. First, we need to apply a logical test to exit the sub procedure.

Table of contents
  • Excel VBA Exit Sub Procedure
    • Examples
      • Example #1
      • Example #2 – On Error Exit the Subprocedure
    • Recommended Articles

Let us construct this in simple terms.

Sub MacroName()

'...

'Some code here

'...

Exit Sub 'Exit the Sub without executing further lines of code below

'...

'This code will be ignored

'...

End Sub

Examples

You can download this VBA Exit Sub Excel Template here – VBA Exit Sub Excel Template

Example #1

For a better example, look at the below code.

Code:

Sub Exit_Example1()

Dim k As Long

For k = 1 To 10

Cells(k, 1).Value = k

Next k

End Sub

exit sub example 1.1

The above code will insert serial numbers from 1 to 10 in cells A1 to A10.

exit sub example 1.2

Now, we want to insert only 5 serial numbers. As soon as the variable “k” value becomes 6, we want to exit the sub.

We will have to add the logical test in excelA logical test in Excel results in an analytical output, either true or false. The equals to operator, “=,” is the most commonly used logical test.read more as IF k = 6 Then Exit Sub.

Code:

Sub Exit_Example1()

Dim k As Long

For k = 1 To 10

If k = 6 Then Exit Sub

'As soon as k value becomes 6 it will ignore all the codes and exit

Cells(k, 1).Value = k

Next k

End Sub

exit sub example 1.3

Now, run the code line by line. Finally, press the F8 key to start the proceedings.

exit sub example 1.8

As of now, the k value is zero.

exit sub example 1.4

To change the k value to 1, press the F8 key again.

exit sub example 1.5

So, the k value is 1. Our code keeps running and will insert 1 to cell A1. Like this, keep running the loop until the value of k becomes 6.

exit sub example 1.6

Now, the value of k is 6. The line of code is about to execute our logical test to exit the subprocedure. If we press the F8 key one more time, it will straight go the entire sub procedure only.

exit sub example 1.7

As we can see, it has highlighted the word “Exit Sub.” Upon pressing the F8 key, it will exit the sub procedure without going to the word “End Sub.”

Example #2 – On Error Exit the Subprocedure

We can also exit the sub procedure when we get the error values. For example, consider the below data for dividing the number1 from 2.

example 2.1

Below is the code to get the division of two numbers.

Code:

Sub Exit_Example2()

Dim k As Long

For k = 2 To 9
Cells(k, 3).Value = Cells(k, 1).Value / Cells(k, 2).Value
Next k

End Sub

example 2.3

As we know, we cannot divide any number by zero. So, if we attempt to do that, we will get the error “Run-time error ’11’: Division by zero.”

example 2.2

To avoid this, as soon as we encounter any error, we will immediately mention my macro to exit the sub procedure. The below code is one such case.

Code:

Sub Exit_Example2()

Dim k As Long

For k = 2 To 9

On Error GoTo ErrorHandler

Cells(k, 3).Value = Cells(k, 1).Value / Cells(k, 2).Value

Next k

ErrorHandler:
             Exit Sub
End Sub

example 2.4

In the above example, we have mentioned the statement “On Error Goto ErrorHandler.” Here, the word “ErrorHandler” is the label we have assigned. As you can see at the bottom of the code, we have mentioned the brand as:

ErrorHandler:
             Exit Sub

As soon as the code encounters an error, it will push the code to jump to the label, and the brand has the “Exit Sub” statement so that it will exit the subprocedure.

Now, we will run the code. First, it will calculate the division until it finds an error.

exit sub example 2.5

As you can see in cell C7, it has encountered an error as “Division by zero,” so it has exited the subprocedure. However, exiting the sub procedure is always dangerous without informing the user. Therefore, we can include a small message box to notify the user of the error.

Code:

Sub Exit_Example2()

Dim k As Long

For k = 2 To 9

On Error GoTo ErrorHandler

Cells(k, 3).Value = Cells(k, 1).Value / Cells(k, 2).Value

Next k

ErrorHandler:

             MsgBox "Error has Occured and the error is:" & vbNewLine & Err.Description

             Exit Sub

End Sub

example 2.6

The above code will show the error message and then exit the subprocedure. While running code, if an error occurs, it will show the message box in VBAVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more like below.

example 2.7

It is more of a reliable way of exiting the Sub procedure.

Recommended Articles

This article is a guide to VBA Exit Sub Procedure. Here, we discuss how to exit the VBA sub procedure when an error occurs in the code with an example and downloadable Excel sheet. You can learn more about VBA from the following articles: –

  • VBA On Error GoTo
  • VBA Delete Sheet
  • Break Points in Excel VBA
  • Do Until Loop in Excel VBA
  • VBA ByRef Argument Type Mismatch

VBA On Error

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.

Insert Module

Now open Subcategory and add any name as we are using On Error, so we have named it as same.

Sub OnError()

End Sub

VBA On Error Example 1-1

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

VBA On Error Example 1-2

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

VBA On Error Example 1-3

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.

VBA On Error Example 1-4

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

VBA On Error Example 1-5

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.

VBA On Error Example 1-6

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

VBA On Error Example 2-1

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

VBA On Error Example 2-2

Now run the code using the F5 key or manually, as shown below.

VBA On Error Example 2-3

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

VBA On Error Example 2-4

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.

 VBA On Error Example 2-5                 

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

Example 3-1

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

Example 3-2

If we run the code, we will get the same error message of Run-time error 11.

Example 3-3

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

Example 3-4

Now run the code again. We will get the same result as the previous example.

Example 3-5

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

Example 4-1

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

Example 4-2

Now, if we run the complete code, then we will get an error message of mathematical error Run time error 11.

Example 4-3

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

Example 4-4

And run the code. This will give a use result on a valid mathematical line, as shown below.

Example 4-5                               

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

Example 4-6

Now run the code by using the F5 key or by pressing the play button, as shown below.

Example 4-7

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–

  1. VBA TRIM
  2. VBA Number Format
  3. VBA Do While Loop
  4. VBA Find

Понравилась статья? Поделить с друзьями:
  • Vba excel error 2015
  • Vba excel automation error вызванный объект был отключен от клиентов
  • Vba error throw
  • Vba error run time error 13 type mismatch
  • Vba error numbers