Vba runtime error 5017

Hello, I found the following Instr function with RegEx. The code Always stuck at 'set found = regEx.Execute(SearchIn). Can anyone help me what's wrong with it? Note that I've also checked the Microsoft VBScript Regular Expressions (1.0 or 5.5) and still is giving the same error.
  1. 09-28-2018, 04:31 PM


    #1

    Instr with RegEx — Runtime error 5017 (RegEx Code provided)

    Hello,

    I found the following Instr function with RegEx.

    The code Always stuck at ‘set found = regEx.Execute(SearchIn).

    Can anyone help me what’s wrong with it?

    Note that I’ve also checked the Microsoft VBScript Regular Expressions (1.0 or 5.5) and still is giving the same error.

    NOTE: Was able to resolve by using «\([0-9]+) ([0-9]+)\» instead of «## ####»

    Last edited by dluhut; 09-28-2018 at 05:21 PM.


  2. 09-28-2018, 04:34 PM


    #2

    Re: Instr with RegEx — Runtime error 5017 (RegEx Code provided)

    Hello
    Can you give more details?
    How did you use the UDF? Upload sample for better explanation

    < —— Please click the little star * next to add reputation if my post helps you
    Visit Forum : From Here


  3. 09-28-2018, 04:48 PM


    #3

    Re: Instr with RegEx — Runtime error 5017 (RegEx Code provided)

    The UDF is basically used in a macro.


  4. 09-28-2018, 05:02 PM


    #4

    Re: Instr with RegEx — Runtime error 5017 (RegEx Code provided)

    I think I realized the problem. The problem is because I have the «». So if I want the «» included in the search, how do I go about doing it?

    Last edited by dluhut; 09-28-2018 at 05:20 PM.


  • Remove From My Forums
  • Вопрос

  • Hello experts,

    I have this code

    Sub ChangeNumberFromFRformatToENformat()

        Dim SectionText As String
        Dim RegEx As Object, RegC As Object, RegM As Object
        Dim i As Integer

       
       
        Set RegEx = CreateObject(«vbscript.regexp»)
        With RegEx
            .Global = True
            .MultiLine = False
            .Pattern = «(?<=^|\s)\d{1,3}(?: \d{3})*(?:,\d{1,3})?(?=\s|$)»

                           

    ‘        .Pattern = «(d{1,3}s(d{3}s)*d{3}(,d{1,3})?|d{1,3},d{1,3})»

                         

            ‘ regular expression used for the macro to recognise FR formated numners
            ‘ regex requires a whitespace or the start of the string before and a whitespace or the end of the string after the number to match.
            End With

       
        For i = 1 To ActiveDocument.Sections.Count()

       
            SectionText = ActiveDocument.Sections(i).Range.Text

           
            If RegEx.test(SectionText) Then
                Set RegC = RegEx.Execute(SectionText)
                ‘ RegC regular expresion matches collection, holding french format numbers

               
                For Each RegM In RegC

           
                    Call ChangeThousandAndDecimalSeparator(RegM.Value)

                   

                Next ‘For Each RegM In RegC

               
                Set RegC = Nothing
                Set RegM = Nothing

               
            End If

       
        Next ‘For i = 6 To ActiveDocument.Sections.Count()

        
        Set RegEx = Nothing

    End Sub

    ===================

    and this regex «(?<=^|\s)\d{1,3}(?: \d{3})*(?:,\d{1,3})?(?=\s|$)»

    When I run the code it gives me this error : Runtime error 5017 «Application-defined or object-defined error » when calling RegEx.test(SectionText), and because the last regex I had raised no such error, I am guessing that the new regex that I wanna use
    has unescpaed characters. But what ??

    Please please help. Thank you for all your time and understandiong!

    kind regards,

    radu

    • Перемещено

      28 ноября 2011 г. 9:09
      needs help with vbscript.regexe (From:Word for Developers)

Ответы

  • Hi Marius

    The better place to ask this would be a forum or other group that supports the library you invoke:
    CreateObject(«vbscript.regexp»)

    Word, itself, doesn’t use RegEx so it’s a bit «hit-and-miss» whether you’ll encounter anyone in this forum that’s familiar with the syntax as used by vbscript.regexp.

    If you wish, I can move this to the «Where is the forum for…» forum where someone there might know a good place to ask the question.


    Cindy Meister, VSTO/Word MVP

    • Предложено в качестве ответа
      Ed Price — MSFTMicrosoft employee
      29 апреля 2012 г. 0:27
    • Помечено в качестве ответа
      Ed Price — MSFTMicrosoft employee
      10 мая 2012 г. 2:33

  • Hi Markus

    I can’t copy your message or start a new thread for you. I can MOVE this discussion, however, and will do so.


    Cindy Meister, VSTO/Word MVP

    • Помечено в качестве ответа
      Ed Price — MSFTMicrosoft employee
      10 мая 2012 г. 2:33

oper25

1 / 1 / 0

Регистрация: 14.04.2011

Сообщений: 30

1

18.12.2011, 19:14. Показов 3319. Ответов 4

Метки нет (Все метки)


Использую следующую схему в ms access:

Visual Basic
1
2
3
4
5
Dim re As New RegExp 
re.Pattern = "(?<=[^0-9])([1-6][0-9]{5})(?![0-9])"
For Each m In re.Execute("101000, Москва, .....")
MsgBox m.Value ' Должен остаться только индекс
Next

И не работает, ошибка — Run-time error: 5017 — method ‘Execute’ of object ‘IRegExp2’ failed

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

18.12.2011, 19:14

Ответы с готовыми решениями:

Программа выдает ошибку
Друг дал прогу не могу разобрать в чем ошибка, звтро сдавать ему

Dim myfile
myfile = RfRufile…

Программа которая выдает платформу компьютера выдает ошибку
unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,…

При решении программа выдаёт значение функции, равное 0 или выдаёт ошибку. Что не так?
#include &lt;iostream&gt;
#include &lt;iomanip&gt;
#include &lt;cmath&gt;
using namespace std;

long Fact(short…

Программа выдаёт ошибку
Программа типа БД, написана на асэмблере.
Данные вводятся нормально, но программа не хочет с ними…

4

Казанский

15131 / 6405 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

18.12.2011, 19:40

2

Если цель — выделить 6-значное число, которое начинается с цифр с 1 до 6, то достаточно

Visual Basic
1
re.Pattern = "[1-6][0-9]{5}"

С такой маской ошибки нет.



0



218 / 50 / 2

Регистрация: 18.02.2010

Сообщений: 81

18.12.2011, 19:57

3

Ошибка тут: «?<=»
Можно использовать только:
(?:шаблон)
(?=шаблон)
(?!шаблон)



0



oper25

1 / 1 / 0

Регистрация: 14.04.2011

Сообщений: 30

19.12.2011, 00:16

 [ТС]

4

Цитата
Сообщение от Казанский
Посмотреть сообщение

Если цель — выделить 6-значное число, которое начинается с цифр с 1 до 6, то достаточно

Visual Basic
1
re.Pattern = "[1-6][0-9]{5}"

С такой маской ошибки нет.

Дело в том, что это число должно быть именно 6-значным. Если будет другое длинное число, то эта маска просто выхватит кусок. Если к 6 знакам числа прилипнет буква, то брать можно, а если длинное число, то не берем. Например «101000Москва» — берем «101000», а 1656518 Иванов И.И., 101000 Москва, брать надо индекс, а не «165651» http://gskinner.com/blog/archi… e_onl.html — через эту утилиту я подобрал строку, но в acctss не заработало

Добавлено через 1 минуту

Цитата
Сообщение от Вождь
Посмотреть сообщение

Ошибка тут: «?<=»
Можно использовать только:
(?:шаблон)
(?=шаблон)
(?!шаблон)

А можете описать, что обозначает каждая строка, либо ссылку на описание ) заранее спасибо!



0



218 / 50 / 2

Регистрация: 18.02.2010

Сообщений: 81

19.12.2011, 03:28

5

Цитата
Сообщение от oper25
Посмотреть сообщение

…что обозначает каждая строка…

(?:шаблон) — комбинация совпадений. Пример: `госпо(?:дин|жа)`
(?=шаблон) — комбинация включений. Пример: `Windows(?=95|98)` подберёт `Windows` в `Windows95`, но не в `WindowsNT`
(?!шаблон) — комбинация исключений. Пример: `Windows(?!95|98)` подберёт `Windows` в `WindowsNT`, но не в `Windows95`

Цитата
Сообщение от oper25
Посмотреть сообщение

…ссылку на описание…

Поищите и скачайте «Microsoft Windows Script Technologies.chm», где описан синтаксис регулярных выражений (Regular Expression Syntax).

Другая документация:
http://ru.wikipedia.org/wiki/Регулярные_выражения
http://www.script-coding.com/WSH/RegExp.html



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

19.12.2011, 03:28

5

При выполнении макросов Excel могут возникнуть ошибки, которые в VBA делят на три категории:

  • Ошибки компиляции
  • Ошибки выполнения
  • Логические ошибки (баги)

Далее мы поговорим о каждом из трёх типов ошибок VBA подробно.

Содержание

  1. Ошибки компиляции
  2. Ошибки выполнения
  3. Перехват ошибок выполнения
  4. Логические ошибки

Ошибки компиляции

Компилятор VBA рассматривает ошибки компиляции как недопустимые и выделяет их в коде ещё до того, как дело дойдёт до запуска макроса.

Если при написании кода допущена синтаксическая ошибка, то редактор VBA сигнализирует об этом немедленно: либо при помощи окна с сообщением, либо выделяя ошибку красным цветом, в зависимости от статуса режима Auto Syntax Check.

Примечание: При включённом режиме Auto Syntax Check каждый раз, при появлении в редакторе Visual Basic во введённом коде синтаксической ошибки, будет показано соответствующее сообщение. Если же этот режим выключен, то редактор VBA продолжит сообщать о синтаксических ошибках, просто выделяя их красным цветом. Опцию Auto Syntax Check можно включить/выключить в меню Tools > Options редактора Visual Basic.

В некоторых случаях ошибка компиляции может быть обнаружена при выполнении компиляции кода, непосредственно перед тем, как макрос будет выполнен. Обычно ошибку компиляции несложно обнаружить и исправить, потому что компилятор VBA даёт информацию о характере и причине ошибки.

Ошибки в Excel VBA

Например, сообщение «Compile error: Variable not defined» при попытке запустить выполнение кода VBA говорит о том, что происходит попытка использовать или обратиться к переменной, которая не была объявлена для текущей области (такая ошибка может возникнуть только если используется Option Explicit).

Ошибки выполнения

Ошибки выполнения возникают в процессе выполнения кода и приводят к остановке выполнения программы. Этот тип ошибок VBA, как правило, также не сложно обнаружить и исправить, так как сообщается информация о характере ошибки и место в коде, где произошла остановка.

Примером такой ошибки может служить попытка выполнить деление на ноль. В результате будет показано сообщение «Run-time error ’11’: Division by zero«.

Ошибки в Excel VBA

В зависимости от структуры проекта VBA, может быть предложено выполнить отладку кода (как показано на рисунке ниже). В этом случае при нажатии на кнопку Debug (в окне сообщения о необходимости отладки) будет выделена цветом строка кода, которая стала причиной ошибки VBA.

Ошибки в Excel VBA

Получив такое сообщение и видя выделенную строку кода, как в приведённом выше примере, обнаружить причину ошибки будет совсем не сложно.

В случае если код сложнее, чем в нашем примере, то, чтобы получить больше информации о причине возникновения ошибки VBA, можно проверить значения используемых переменных. В редакторе VBA для этого достаточно навести указатель мыши на имя переменной, или можно открыть окно отслеживания локальных переменных (в меню редактора View > Locals Window).

Коды различных ошибок выполнения расшифрованы на сайте Microsoft Support (на английском). Наиболее часто встречающиеся ошибки VBA перечислены в этой таблице:

5 Недопустимый вызов процедуры (Invalid procedure call)
7 Недостаточно памяти (Out of memory)
9 Индекс вне заданного диапазона (Subscript out of range)

Эта ошибка возникает при попытке обратиться к элементу массива за пределами заданного размера массива – например, если объявлен массив с индексами от 1 до 10, а мы пытаемся обратиться к элементу этого же массива с индексом 11.

11 Деление на ноль (Division by zero)
13 Несоответствие типа (Type mismatch)

Эта ошибка возникает при попытке присвоить переменной значение не соответствующего типа – например, объявлена переменная i типа Integer, и происходит попытка присвоить ей значение строкового типа.

53 Файл не найден (File not found)

Иногда возникает при попытке открыть не существующий файл.

Перехват ошибок выполнения

Не все ошибки выполнения бывают вызваны недочётами в коде. Например, ошибки VBA не удастся избежать, если для работы макроса необходимо открыть файл с данными, а этого файла не существует. В таких случаях признаком профессионализма будет перехват ошибок и написание кода VBA, который будет выполняться при их возникновении. Таким образом, вместо неприятных сбоев будет происходить изящное завершение работы макроса.

Для того, чтобы помочь справиться с возникающими ошибками, VBA предоставляет разработчику операторы On Error и Resume. Эти операторы отслеживают ошибки и направляют выполнение макроса в специальный раздел кода VBA, в котором происходит обработка ошибки. После выполнения кода обработки ошибки, работа программы может быть продолжена с того места, где возникла ошибка, или макрос может быть остановлен полностью. Далее это показано на примере.

'Процедура Sub присваивает переменным Val1 и Val2 значения,
'хранящиеся в ячейках A1 и B1 рабочей книги Data.xlsx расположенной в каталоге C:Documents and Settings

Sub Set_Values(Val1 As Double, Val2 As Double)

   Dim DataWorkbook As Workbook

   On Error GoTo ErrorHandling

      'Открываем рабочую книгу с данными

      Set DataWorkbook = Workbooks.Open("C:Documents and SettingsData")

      'Присваиваем переменным Val1 и Val2 данные из рабочей книги DataWorkbook

      Val1 = Sheets("Лист1").Cells(1, 1)
      Val2 = Sheets("Лист1").Cells(1, 2)

      DataWorkbook.Close

   Exit Sub

ErrorHandling:

   'Если файл не найден, предлагаем пользователю разместить его в
   'нужном месте и продолжить работу

   MsgBox "Рабочая книга не найдена! " & _
      "Пожалуйста добавьте книгу Data.xlsx в каталог C:Documents and Settings и нажмите OK."

   Resume

End Sub

В этом коде производится попытка открыть файл Excel с именем Data. Если файл не найден, то пользователю будет предложено поместить этот файл в нужную папку. После того, как пользователь сделает это и нажмёт ОК, выполнение кода продолжится, и попытка открыть этот файл повторится. При желании вместо попытки открыть нужный файл, выполнение процедуры Sub может быть прервано в этом месте при помощи команды Exit Sub.

Логические ошибки

Логические ошибки (или баги) возникают в процессе выполнения кода VBA, но позволяют ему выполняться до самого завершения. Правда в результате могут выполняться не те действия, которые ожидалось, и может быть получен неверный результат. Такие ошибки обнаружить и исправить труднее всего, так как компилятор VBA их не распознаёт и не может указать на них так, как это происходит с ошибками компиляции и выполнения.

Например, при создании макроса в процедуре случайно были просуммированы не те переменные, которые требовалось просуммировать. Результат будет ошибочным, но макрос будет продолжать выполняться до завершения.

Редактор Excel VBA предоставляет набор инструментов отладки, которые помогут найти и исправить логические ошибки в коде VBA. В данной статье мы не будем рассматривать подробно эти инструменты. Любознательный пользователь может найти обзор инструментов отладки VBA на сайте Microsoft Help & Support (на английском).

Оцените качество статьи. Нам важно ваше мнение:

Just like any other programming language, VBA has no luck when it comes to errors and you have to deal with them, no matter what. They may come from different sources, like bad coding, impossible operations (like zero division), or unexpected errors.

The best way to deal with it is to have a proper understanding of all the possible outcomes of the result that you could get with code. Look at the below example where we have a VBA code that calculates the square root of the number using the value which you have in the selected cell.

Sub Square_Root()
ActiveCell.Value = ActiveCell.Value ^ (1 / 2)
End Sub

But if the active cell has a value other than a number, you’ll get a run-time error, just like below.

Error Settings in VBA (Error Trapping)

In the VBA option, you can configure the setting to deal with errors before you start writing codes. To open the VBA settings, go to Tools ➤ Options ➤ Generals ➤ Error Trapping. Here you have three options which you can use.

  • Break on All Errors: If you have this option activated, VBA will stop the code for all types of errors even if you have used all kinds of error handling techniques.
  • Break-in Class Module: With this option, VBA will stop all your codes that are not handled by any technique. And if you’re using objects such as Userforms, it will also break within those objects and highlight the exact line where the error is.
  • Break on Unhandled Errors: This is the default setting that helps you to know about all the errors where you are not using any error handling technique and stop the code for all the unhandled errors. (But, if you’re using objects such as Userforms, this will not highlight the line causing the error in the object but will only highlight the line that’s referring to that object).

Types of VBA Errors

To understand VBA errors, you can split them into four categories, and below is the explanation of these types of errors.

1. Syntax Errors

While writing VBA code you need to follow a particular Syntax and when you skip it or don’t write it in the way it should be you can face SYNTAX error (also called Language error). It’s like typos that you do while writing your codes.

Well, VBA helps you by pointing out these errors by showing an error message. You just need to make sure you have “Auto Syntax Check” activated in your VB editor.

Go to the Tool ➤ Options and make sure to tick the “Auto Syntax Check”. With this, whenever you make a SYNTAX error, VBA will show an error message.

But if “Auto Syntax Check” is disabled VBA still highlights the line of code with the error but won’t show the error message.

2. Compile Errors

It comes when you write code to perform an activity, but that activity is not valid or can’t be performed by VBA. The best example is where you have a code using the IF statement but missed to add END IF at the end of the statement and now when you run this VBA will show you a compilation error message.

Apart from this, there are some other examples of compile errors:

  • Using For without Next (For Next).
  • Select without End Select (Select Case).
  • Not Declaring a Variable when you have “Option Explicit” enabled.
  • Calling a Sub/Function that does not exist.

3. Runtime Errors

A runtime error occurs at the time of executing the code. Remember the example, I shared with you above when the code calculated the square root of a number.

When a runtime error occurs while running code, it stops the code and shows you the error dialog box and that error box talks about the nature of the error you have. Let’s say you have written a code that opens a workbook from the location which you have specified but now that workbook is relocated or deleted by someone.

So, when you run the code, VBA will show you a runtime error as it can’t find that file on that location. The message you get in a run time error describes the reason which helps you to understand the reason for the error.

And when a runtime error occurs it stops the execution of the code. If you click on the “Debug” button it shows you the line of code that has that error by highlighting it yellow. Or you can click on the “End” button to stop the code to execute and close the error message.

4. Logical Error

It’s not an error but a mistake while writing code. These types of errors sometimes can give you nuts while finding them and correcting them.

Let’s say you write code and while declaring a variable you used the wrong data type, or you have used the wrong calculation steps. In this case, your code will work fine, and you won’t find this error easily. The best way to deal with this kind of problem is to run each line of code one by one.

Using Debug Tools in VBA

VBA provides you a set of tools to debug your code and remove bugs from your codes.

1. Compile VBA Project

In Visual Basic Editor, there’s an option that you can use instantly after completing your code. These compile options scan each line of your code and show a message box if there is an error in your code.

Note: Compile VBA option only traces Syntax and Compile errors, not runtime errors as these errors only rise when a code is running. To use Compile VBA Project, go to ➤ Debug ➤ Compile VBA Project.

Once you run “Compile VBA Project” and you have no error in your code, the options will be greyed out.

2. Run Each Line of Code One by One

This is how I do it. When I complete a code, I simply run it line by line to check if there’s an error occurring. It may take time, but it helps you to get to about all the errors (Syntax, Compile, and Run-Time).

On the “Debug Toolbar”, there’s a button “Step In” which you can use to execute a code line by line or you can simply press F8 to execute a single line and then press it again to execute the next line in the code.

Using “On ERROR” Statement to Handle VBA Errors

It’s important to check your codes and find possible errors in all the debugging ways you have. But, the best and most effective way is to create error-handling statements that can deal with an error and make your code flawless while executing. Let’s learn about these statements. When an error occurs in a VBA code the best possible ways to handle that error can be:

  • Let the VBA ignore the error and execute the code
  • Let a special set of statements to run when an error occurs.

In both solutions, you can use “On Error” statements. Below four “On Error” statements that you can use. And now, let’s look at each statement one by one.

1. On Error Resume Next

This simple line of code lets VBA continue executing the code despite the occurrence of an error. The IDEA is simple: Move to the next line of the code if there’s an error found somewhere while executing.

In the below code, you have two lines of code:

  • The first line says the value  of cell A1 is 25 divided by 0
  • And the second line says the value cell A2 is 10 divided by 5

Now there’s a problem with the code which you have inline one. As you know if you divide anything with 0 the result will be an error.  So, when you run this code VBA will show an error message “Run-time error ‘11’ Division by Zero” and stop the execution.

But when you add the “On Error Resume Next” at the very beginning of the code and run the code, VBA simply skips that line of code where the error occurs and continues with the second line and add that value in cell A2.

Sub myDivide()
On Error Resume Next
    Range("A1").Value = 25 / 0
    Range("A2").Value = 10 / 5
End Sub

So, whenever you want your code to get executed despite an error occurring anywhere simply use the “On Error Resume Next” statement in your code.

But here’s one more thing you need to note down: It will only skip errors that occur after it.

Let’s say if an error occurs at line 5 and you have added “On Error Resume Next” on line 8 then it would not skip that error.  So, the best way is to add it as the first line of the code in the procedure.

2. On Error GoTo 0

It’s the default behavior of VBA that when an error occurred it stops the execution of the code.

Well, using “On Error GoTo 0” make no difference in your code. VBA will simply stop the code and show a message with a description of the error. Then why would I bother to use it? Smart Question. Let’s use the example you have used above in “On Error Resume Next”.

In this code whenever an error will occur VBA will resume to the next line of code and run it and you won’t see any error message. But let’s say you have more lines in your code and you don’t want to surpass those lines if there’s an error in the code.

So, if you enter “On Error GoTo 0” after the second line of code it will restore the VBA’s default error handler which shows error messages each time an error occurs.

3. On Error GoTo [Label]

Think about a place in a building where you can head up in an emergency. In the same way, using “On Error GoTo [Label]”, you can simply create a separate block of code in your main code to deal with an error.

Actually, “On Error GoTo [Label]” is a far better and more convenient way to deal with errors. In the below code, you have “On Error GoTo Oh!Error” now in this line statement the word “Oh!Error” is the label.

If you look at the end of the code where you have a specific starting with the label name and then a code for a message box with a message about the code.

Now, what happens if an error occurs the VBA will jump to the label “Oh!Error” and run the block of code which you have after that label.

But there’s one thing you need to take care of: If an error doesn’t occur even then the label you have in your code will get executed. There are two things you need to do:

  • First, make sure to add your Error label at the end of the code.
  • Second, add an “Exit Sub” before the error label.

With this, you’ll benefit in both situations. Let’s say if an error occurs and VBA jumps to the label you specified there would only be code from the label itself to code. And if an error doesn’t occur “Exit Sub” statement which you have before the label will exit the procedure without executing the error label.

4. On Error GoTo -1

Before we get into this, let me share something with you.  When an error occurs in a code VBA stores that error log in its memory and only clears it when the routine ends.

O VBA! Live in Present

To deal with the second error in a VBA code you need to clear the first error from VBA’s memory. In the below code, you have two “On Error GoTo [Label]” statements that deal with errors from two different blocks of code.

But if you run this code, when the second error VBA won’t jump to the label which you have defined and instead show the error message “Type Mismatch”.

Sub Square_Root()
On Error GoTo myError1
Range("A1").Value = Range("A1").Value ^ (1 / 2)
myError1:
MsgBox "There's some problem with the value you have in the cell A1."
On Error GoTo myError2
Range("A2").Value = Range("A2").Value ^ (1 / 2)
myError2:
MsgBox "There's some problem with the value you have in the cell A2."
End Sub

To fix this problem you can use “On Error GoTo -1” which makes VBA remove the current error from its storage memory.

Sub Square_Root()
 On Error GoTo myError1
 Range("A1").Value = Range("A1").Value ^ (1 / 2)
 myError1:
 MsgBox "There's some problem with the value you have in the cell A1."
 On Error GoTo -1
 On Error GoTo myError2
 Range("A2").Value = Range("A2").Value ^ (1 / 2)
 myError2:
 MsgBox "There's some problem with the value you have in the cell A2."
 End Sub

Now when you run this code, “On Error GoTo -1” removes the error from the memory and VBA deals with the error in the second statement as you want.

What Else Do I Need to Know to Handle Errors in VBA?

Apart from using error handling techniques, there are a few other things that you can use to deal with errors in a better way.

Err Object

When an error occurred while executing of code, you can use the Err object to get details about that error. There are a few properties and methods which you can use with Err object. Let’s learn them one by one.

Properties

Below are the properties which you can use with the Err object:

  • Err.Number: With an error occurred there’s a number stored in the Err Object. In the below code, when occurred the message box will show the error number.  
  • Err.Description: This property shows the description of the error which can help you to understand the reason for the error.
  • Err.Source: This property shows you in which project the error has occurred.
  • Err.HelpContext: This property returns the help context id for the error in the help file.
  • Err.HelpContext: This is a string value for the location of the help file.

Normally when you are dealing with errors using error handling techniques you won’t be using the Err Object that much in your codes. But below is a simple example to use it.

Sub Square_Root()
On Error GoTo myError1
    Range("A1").Value = Sqr(Range("A1").Value)
Exit Sub
myError1:
    MsgBox "There's some problem with the value you have in the cell A1." & vbCrLf & _
                "Error Number: " & Err.Number  & vbCrLf & _
                "Error Description: " & Err.Description
End Sub

When you run the above code, and if an error occurred, it will show a message box with the error number and description of the error.

Methods

With Err Object there are two methods that you can also use.

  • Err.Clear: This method clears the error number and error description from VBA’s memory (It’s different from “On Error GoTo -1” as it doesn’t completely reset the error).
  • Err.Raise: With this method, you can generate a run time error in your code intentionally, and below is the syntax which needs to follow:

Err.Raise [number], [source], [description], [helpfile], [helpcontext]

Quick Tips on Error Handling

Here are a few quick tips which you can use to deal with VBA errors in a better way.

  • Use “On Error Resume Next” only when you know for sure about an error to occur and it’s OK to skip the line of code with an error and it’s safe to skip to the next line.
  • The best way to deal with run-time errors is by using “Error Handler” with “On Error GoTo [Label]”. This ensures that whenever the error occurs you will know about it, but it won’t show that nasty error message.
  • Whenever you use the error handler make sure to use “Exit Sub” before it.

There’s More

Below are some of the links which could be useful for you to learn more about error handling in VBA, make sure to check out all of these:

Type Mismatch (Error 13) | Runtime (Error 1004) | Object Required (Error 424) | Out of Memory (Error 7) | Object Doesn’t Support this Property or Method (Error 438) | Invalid Procedure Call or Argument (Error 5) | Overflow (Error 6) | Automation error (Error 440) | VBA Error 400 | VBA Subscript Out of Range Runtime Error 9

Понравилась статья? Поделить с друзьями:
  • Vba runtime error 462 word
  • Vba runtime error 429 activex component can t create object
  • Vba runtime error 2147467259
  • Vba runtime error 13 type mismatch как исправить
  • Vba run time error 76 path not found