Макрос если ошибка то дальше

 

Framed

Пользователь

Сообщений: 223
Регистрация: 25.01.2018

#1

04.03.2019 19:39:20

Коллеги, приветствую,

Немного запутался в теме про обработчик ошибок, хотя, скорее всего, я нашёл ответ на вопрос в

этой теме

, просто не могу его понять до конца.

Необходимо, чтобы в случае ошибки, которая возникает в определенный момент в коде, часть кода пропускалась, появлялся MsgBox с определенным текстом, после чего макрос продолжал бы работать в нормальном режиме (если будет какая-нибудь другая ошибка далее — выскочит диалоговое окно).

Знаю, что задача простая, ну вот туплю что-то…

Код
            On Error GoTo ErrorHandler            
            Set iWb = GetObject("C:UsersA670669DesktopSCR_Managers.xlsx")
            iLastRowSCR = iWb.Sheets(1).Cells(Rows.Count, 1).End(xlUp).row
            Set iBodySCR = iWb.Sheets(1).Range("B2:M" & iLastRowSCR)
            iWb.Names.Add Name:="BodySCR", RefersTo:=iBodySCR
            With .ListColumns("Rate").DataBodyRange
                .Formula = "=IFERROR(VLOOKUP(A3,SCR_Managers.xlsx!BodySCR,12,0),0)"
                .Cells.Value = .Cells.Value
            End With
            iWb.Close False
ErrorHandler:
            MsgBox "Произошла ошибка"
            On Error Resume Next

На данный момент все как надо, только вот когда даже ошибки нет вылезает MsgBox.

Заранее спасибо.

P.S. Как-то криво написал название темы, должна была быть VBA: Обработчик ошибок, пропуск кода и продолжение выполнения макроса.

Изменено: Framed05.03.2019 00:54:10

 

Anchoret

Пользователь

Сообщений: 1065
Регистрация: 01.01.1970

Anchoret

#2

04.03.2019 19:44:33

Код
On Error Resume Next
If Err then Goto ...
 

Framed

Пользователь

Сообщений: 223
Регистрация: 25.01.2018

#3

04.03.2019 19:52:06

Anchoret, вот так?

Код
 On Error Resume Next
            MsgBox "Произошла ошибка"
            If Err Then GoTo ErrorHandler
            Set iWb = GetObject("C:UsersA670669DesktopSCR_Managers.xlsx")
            iLastRowSCR = iWb.Sheets(1).Cells(Rows.Count, 1).End(xlUp).row
            Set iBodySCR = iWb.Sheets(1).Range("B2:M" & iLastRowSCR)
            iWb.Names.Add Name:="BodySCR", RefersTo:=iBodySCR
            With .ListColumns("Rate").DataBodyRange
                .Formula = "=IFERROR(VLOOKUP(A3,SCR_Managers.xlsx!BodySCR,12,0),0)"
                .Cells.Value = .Cells.Value
            End With
            iWb.Close False
ErrorHandler:






 

Sanja

Пользователь

Сообщений: 14853
Регистрация: 10.01.2013

#4

04.03.2019 19:54:37

Цитата
Framed написал: только вот когда даже ошибки нет вылезает MsgBox

Обработчик ошибок поместите в самый конец кода, а перед ним должна быть строка Exit Sub

Код
On Error GoTo ErrorHandler
    Set iWb = GetObject("C:UsersA670669DesktopSCR_Managers.xlsx")
    iLastRowSCR = iWb.Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row
    Set iBodySCR = iWb.Sheets(1).Range("B2:M" & iLastRowSCR)
    iWb.Names.Add Name:="BodySCR", RefersTo:=iBodySCR
    With .ListColumns("Rate").DataBodyRange
        .Formula = "=IFERROR(VLOOKUP(A3,SCR_Managers.xlsx!BodySCR,12,0),0)"
        .Cells.Value = .Cells.Value
    End With
    iWb.Close False
    Exit Sub
'обработчик ошибок
ErrorHandler:
    MsgBox "Произошла ошибка"
End Sub

Согласие есть продукт при полном непротивлении сторон.

 

Framed

Пользователь

Сообщений: 223
Регистрация: 25.01.2018

#5

04.03.2019 20:03:30

Sanja, спасибо, но разве Exit Sub не остановит выполнение всего макроса, если ошибки не будет?

Я уточню, а то мне кажется, я плохо объяснил в шапке.

Код
'Код
'Код
'Код
 On Error GoTo ErrorHandler
            Set iWb = GetObject("C:UsersA670669DesktopSCR_Managers.xlsx")
            iLastRowSCR = iWb.Sheets(1).Cells(Rows.Count, 1).End(xlUp).row
            Set iBodySCR = iWb.Sheets(1).Range("B2:M" & iLastRowSCR)
            iWb.Names.Add Name:="BodySCR", RefersTo:=iBodySCR
            With .ListColumns("Rate").DataBodyRange
                .Formula = "=IFERROR(VLOOKUP(A3,SCR_Managers.xlsx!BodySCR,12,0),0)"
                .Cells.Value = .Cells.Value
            End With
            iWb.Close False
ErrorHandler:
            MsgBox "Произошла ошибка"
'Код
'Код
'Код

Выполняется макрос, и вот на 5 строке может выскочить ошибка, например, если файла нет, или его имя неверное. Мне нужно, чтобы в этом случае, часть кода 5-13 строка игнорировалась, не выполнялась и выскочил бы MsgBox c текстом, например, «Нет файла или имя некорректно». Далее код, который идет после ErrorHandler должен выполняться в обычном режиме (обычный режим для меня — это когда дальнейшие ошибки не вернут меня к ErrorHandler, простите за убогое объяснение).

В случае же, если ошибки на 5 строке моего примера не возникнет — код работает в штатном режиме.

Изменено: Framed04.03.2019 20:03:53

 

Anchoret

Пользователь

Сообщений: 1065
Регистрация: 01.01.1970

Anchoret

#6

04.03.2019 20:06:40

Framed,

Код
On Error Resume Next

перед строкой, в которой вероятна ошибка

Код
If Err then Goto ...

после такой строки. Ну и замечание от Sanja,

 

Framed

Пользователь

Сообщений: 223
Регистрация: 25.01.2018

Как-то не выходит. Дальнейшие ошибки в коде игнорируются, MsgBox вылезает, даже если ошибки не произошло.

 

БМВ

Модератор

Сообщений: 21681
Регистрация: 28.12.2016

Excel 2013, 2016

#8

04.03.2019 20:25:02

только наверно так

Код
'Код
'Код
'Код
 On Error resume next
            Set iWb = GetObject("C:UsersA670669DesktopSCR_Managers.xlsx")
            if err =0 then
                 iLastRowSCR = iWb.Sheets(1).Cells(Rows.Count, 1).End(xlUp).row
                 Set iBodySCR = iWb.Sheets(1).Range("B2:M" & iLastRowSCR)
                iWb.Names.Add Name:="BodySCR", RefersTo:=iBodySCR
                With .ListColumns("Rate").DataBodyRange
                    .Formula = "=IFERROR(VLOOKUP(A3,SCR_Managers.xlsx!BodySCR,12,0),0)"
                    .Cells.Value = .Cells.Value
                End With
                iWb.Close False
           else
                MsgBox "Произошла ошибка"
                err.clear  '  или on error goto 0
          end if
'Код
'Код
'Код
 

По вопросам из тем форума, личку не читаю.

 

Framed

Пользователь

Сообщений: 223
Регистрация: 25.01.2018

БМВ, спасибо, все отлично, только теперь в случае ошибки ниже End If, VBA продолжит выполнение кода, даже если, к примеру, название листа out of range и так далее.  

 

БМВ

Модератор

Сообщений: 21681
Регистрация: 28.12.2016

Excel 2013, 2016

Framed,  я не зря там написал ‘  или on error goto 0
В зависимости от потребностей или сбросить ошибку или и сбросить и прекратить обработку ошибок.
Конечно и через переход на метки можно сделать, но я отвык.

Изменено: БМВ04.03.2019 20:49:50

По вопросам из тем форума, личку не читаю.

 

Framed

Пользователь

Сообщений: 223
Регистрация: 25.01.2018

#11

04.03.2019 20:52:16

БМВ, простите, я проглядел. Спасибо большое за помощь, теперь я понял больше, без вас не разобрался бы.

Цитата
БМВ написал: Конечно и через переход на метки можно сделать, но я отвык.

Я где-то читал, что метки не приветствуются в VBA. Да и мне привычнее с операторами условия  :)  

 

БМВ

Модератор

Сообщений: 21681
Регистрация: 28.12.2016

Excel 2013, 2016

По вопросам из тем форума, личку не читаю.

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

#13

05.03.2019 00:23:09

Цитата
Framed написал: метки не приветствуются в VBA.

Метки не беда, если не злоупотреблять и если они не нарушаюют (

не сильно нарушают

) структуру кода

 

Nordheim

Пользователь

Сообщений: 3154
Регистрация: 18.04.2017

Причина ошибки в данном куске кода в чем заключается?

«Все гениальное просто, а все простое гениально!!!»

 

Framed

Пользователь

Сообщений: 223
Регистрация: 25.01.2018

Nordheim, потенциально ошибка в том, что файл с таким названием может отсутствовать на рабочем столе у юзера. Этот файл (если он есть) в моем коде открывается, оттуда ВПР-ом подтягивается информация, после чего он закрывается. Если такого файла нет — мне нужно было, чтобы:

1. Выводилось сообщение со специальным текстом, т.е. MsgBox;
2. Пропускался кусок кода (который открывает файл, создает именной диапазон для ВПР, подтягивает куда надо данные с этого листа с помощью ВПР, превращает формулы в значения и закрывает книгу);
3. Макрос снова бы работал в обычном режиме (то есть в режиме «on error go to 0»).

Вообще, мне помогли и тему можно было закрывать, но раз уж вы спросили :)

БМВ, да, и я даже прочитал это несколько раз перед тем, как создать тему. Просто, откровенно говоря, не доходило до меня, как это правильно использовать; примеры из гугла не добавили ясности. Одним словом, еще учиться и учиться.

Изменено: Framed05.03.2019 14:33:07

 

Nordheim

Пользователь

Сообщений: 3154
Регистрация: 18.04.2017

#16

05.03.2019 14:45:40

Цитата
Framed написал:
Nordheim , потенциально ошибка в том, что файл с таким названием может отсутствовать на рабочем столе у юзера.

А если так:

Код
Sub test()
    Dim fname$, iPath$
    iPath = "C:UsersA670669DesktopSCR_Managers.xlsx"
    fname = Dir(iPath)
    If fname <> "" Then
        'обработка если файл существует
    Else: MsgBox "Произошла ошибка"
    End If
End Sub

Никакого On Error

PS:
Обработчик ошибок это конечно хорошо, вставил в начало и никаких проблем с кодом, зато потом вылезет какая ни-будь

«бяка»

в отчетах.

Изменено: Nordheim05.03.2019 14:48:24

«Все гениальное просто, а все простое гениально!!!»

 

Jack Famous

Пользователь

Сообщений: 11140
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

#17

05.03.2019 15:02:02

Framed, очень много чего вам посоветовали — лень читать всё))
1. В большинстве случаев от меток можно абсолютно безболезненно избавится, но иногда они помогают. Например, можно избежать «ветвления» кода далеко «вправо» — вот

ссылка

на тему с холиваром)))

Итак, в чём проблема… Всё просто — код доходит до строки ErrorHandler: MsgBox «Произошла ошибка» и выводит сообщение об ошибке (как и должен). Чтобы этого избежать, я обычно делаю, как в #4 (Sanja), но можно и «в лоб» обойти:

Код
GoTo nx
            iWb.Close False
ErrorHandler:
            MsgBox "Произошла ошибка"
nx:

— в таком случае, если мы дошли до GoTo nx, то просто «перепрыгиваем» ErrorHandler на метку nx. Если же произойдёт ошибка, то макрос «перепрыгнет» уже к метке ErrorHandler, минуя GoTo nx.

P.S.:

скорее всего, в вашем случае никакого On Error GoTo ErrorHandler не нужно — это подтверждает и наличие примеров, где легко без него можно обойтись. Я использую метки в основном, если нужно вернуться «выше по коду» (повтор ввода информации пользователем в случае ошибки) или, как уже сказал, чтобы избежать «ветвления» (многоуровневых вложенных «If—Else—End If»).
Но дело (как кодить) исключительно ВАШЕ  ;)

Изменено: Jack Famous05.03.2019 15:34:40

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

БМВ

Модератор

Сообщений: 21681
Регистрация: 28.12.2016

Excel 2013, 2016

#18

05.03.2019 15:21:22

Nordheim,
тут есть подвох, я с таким встречаюсь регулярно (правда не со скриптамии, но не суть)

Код
    iPath = "C:UsersA670669DesktopГод 2019Документы раздолбая" _
          & "Результаты совещания по вопросам бездумного использования длинных имен файлов и каталогов" _
          & "Выступление главного систематизатора……SCR_Managers.xlsx"

Короче, при полном пути более 260 символов, файл есть, он виден, но открыть его не возможно, впрочем как и скопировать или удалить, понятно что лучше в этом случае обработать длину пути, но порой проще просто обратится и обработать ошибку.
Вариант 2, это уже последствия сетевого доступа к общим файлам. При переносе файлов или каталогов права не наследуются от каталога в который поместили файлы , а сохраняются прежними. Это может привести к тому что также видеть видно, а вот прочесть никак. И в этом случае без обработки ошибки не обойтись.

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

Jack Famous, так как я родом из VBS, а там нет Resume, то перешел на метку по ошибке, обратно не вернешься, что означает не продолжить с того же места. а это означает или куча меток и отдельные обработчики для каждой ошибки или …..

По вопросам из тем форума, личку не читаю.

 

Jack Famous

Пользователь

Сообщений: 11140
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

#19

05.03.2019 15:32:09

Цитата
БМВ: я родом из VBS

а я, стало быть, из VBA и могу использовать крутые штуки типа возврата наверх))

Вот такая, например

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

Nordheim

Пользователь

Сообщений: 3154
Регистрация: 18.04.2017

#20

05.03.2019 15:32:29

БМВ, На сколько я понимаю в данном случае путь прописывается руками, и визуально видно сколько символов.

Цитата
БМВ написал:
при полном пути более 260 символов, файл есть, он виден, но открыть его не возможно

Не сталкивался, потому наверное, что c Excel работаю постольку поскольку, это больше для саморазвития (интересные задания иногда встречаются).
Но теперь буду знать, а обработчиками в основном пользуюсь либо для заполнения коллекции либо в цикле где неправильный тип данных указывают и цикл не завершается пока ошибка не будет устранена.  ;)

«Все гениальное просто, а все простое гениально!!!»

 

БМВ

Модератор

Сообщений: 21681
Регистрация: 28.12.2016

Excel 2013, 2016

#21

05.03.2019 16:15:03

Цитата
Nordheim написал:
На сколько я понимаю в данном случае путь прописывается руками, и визуально видно сколько символов

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

По вопросам из тем форума, личку не читаю.

 

Казанский

Пользователь

Сообщений: 8839
Регистрация: 11.01.2013

#22

05.03.2019 16:56:51

Цитата
БМВ написал:
так как я родом из VBS, а там нет Resume, то перешел на метку по ошибке, обратно не вернешься

Забыл, забыл ты свою родину ;) Нет там меток, и GoTo только в конструкции On Error GoTo 0.

 

Framed

Пользователь

Сообщений: 223
Регистрация: 25.01.2018

Jack Famous, спасибо за разъяснения;
Nordheim, вам тоже большое спасибо, на самом деле, мне очень понравилось это решение, как и решение участника БМВ.
БМВ, спасибо за полезную информацию про ограничение.

Все-таки поясню: планируется, что файл, наличие которого проверяется, я буду высылать юзерам ежемесячно. У него относительно постоянная форма, меняются лишь данные. Соответственно, название файлу задаю тоже я. Файл носит вспомогательный характер. Вряд ли юзеры будут его переименовывать (я обязательно скажу, чтобы этого не делали) — их задача состоит лишь в том, чтобы один раз скопировать этот файл из Аутлука и куда-нибудь его закинуть, а после прописать корректный путь в VBA (а вот это им придется делать в любом случае самим, увы).

 

БМВ

Модератор

Сообщений: 21681
Регистрация: 28.12.2016

Excel 2013, 2016

#24

05.03.2019 18:47:08

Цитата
Казанский написал:
Забыл, забыл ты свою родину

:-) вооот , там даже шанса не было :-) По сему и не применяю :-)

По вопросам из тем форума, личку не читаю.

 

Nordheim

Пользователь

Сообщений: 3154
Регистрация: 18.04.2017

#25

05.03.2019 19:11:54

Цитата
Framed написал:
(а вот это им придется делать в любом случае самим, увы)

А если написать юзерам что бы сохранили файл с макросом и файл из которого берутся данные, в одну папку, то и прописывать ничего не нужно. Как вариант, можно сделать выбор файла.

«Все гениальное просто, а все простое гениально!!!»

 

RAN

Пользователь

Сообщений: 7190
Регистрация: 21.12.2012

#26

05.03.2019 19:48:22

Цитата
БМВ написал:
Короче, при полном пути более 260 символов

Еще короче. Для Exsel, кажется, 218 символов. Попадал.  :D

 

БМВ

Модератор

Сообщений: 21681
Регистрация: 28.12.2016

Excel 2013, 2016

#27

06.03.2019 08:03:50

Off

Цитата
RAN написал:
Для Exsel, кажется, 218 символов

Это не совсем про файл, а скорее про обращение к нему из самого Excel

https://support.microsoft.com/en-us/help/213983/error-message-when-you-open-or-save-a-file-in-microsoft-excel-filename

This behavior is based on a 256-character limitation in Excel for creating links to another file. This limit of 218 characters for the path name is based on the following:•Up to 31 characters in a sheet name.

•Apostrophes and brackets used to denote the workbook name.

•An exclamation point.

•A cell reference.

For example, the path for a file might resemple the following:

  ‘c:excelpersonal…[my workbook.xls]up_to_31_char_sheetname’!$A$1

Если перевести кратко, то, для работы с другой книгой, ссылка не может быть больше 256 символов, включая дополнительные символы (скобки,апострофы, восклицательный знак), имя листа  и диапазон.   если учесть что  Адрес может быть $AAA$1000000 (12 сим) +31 на имя листа + 5 на спец символы, то на путь останется менее 218ти
256-12-31-5=208

По вопросам из тем форума, личку не читаю.

 

Nordheim

Пользователь

Сообщений: 3154
Регистрация: 18.04.2017

#28

06.03.2019 08:54:26

В дополнении  

Цитата
Nordheim написал:
А если написать юзерам что бы сохранили файл с макросом и файл из которого берутся данные, в одну папку

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

Прикрепленные файлы

  • Книга1.xlsm (16.3 КБ)

«Все гениальное просто, а все простое гениально!!!»

 

Framed

Пользователь

Сообщений: 223
Регистрация: 25.01.2018

#29

13.03.2019 17:36:49

Коллеги, прошу прощения заранее, что поднимаю старую тему и задаю в ней вопрос, но он связан с тем же макросом и с тем, что мне ответил пользователь Nordheim.

Цитата
Nordheim написал:
А если написать юзерам что бы сохранили файл с макросом

Файлы не с макросом, потому что модуль с ним находится в личной книге макросов.

Цитата
Nordheim написал:
Как вариант, можно сделать выбор файла.

Вот тут я хотел бы уточнить, если вы не против. Можно ли сделать такой алгоритм (но я точно не знаю, в самом макросе, или сделать отдельный), который поможет юзеру выбрать вспомогательный файл (как с сохранением, с помощью окна), а основной макрос бы ссылался на выбранный файл.

Зачем это нужно: планируются, что такие вспомогательные файлы будут отправляться юзерам раз в месяц, соответственно, можно их просто назвать одним именем и заменять один другим (как и реализованно в данный момент), но было бы лучше, если бы они сохранялись в специально созданной для этого папке, а юзеры могли бы просто «переключаться» между файлами, из которых нужно брать инфу.  

 

Jack Famous

Пользователь

Сообщений: 11140
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

#30

13.03.2019 18:02:32

Framed, если вопрос не связан с темой (Обработчик ошибок, пропуск куска кода), то создавайте новую

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

In this Article

  • VBA Errors Cheat Sheet
    • Errors
  • VBA Error Handling
  • VBA On Error Statement
    • On Error GoTo 0
    • On Error Resume Next
    • Err.Number, Err.Clear, and Catching Errors
    • On Error GoTo Line
  • VBA IsError
  • If Error VBA
  • VBA Error Types
    • Runtime Errors
    • Syntax Errors
    • Compile Errors
    • Debug > Compile
    • OverFlow Error
  • Other VBA Error Terms
    • VBA Catch Error
    • VBA Ignore Error
    • VBA Throw Error / Err.Raise
    • VBA Error Trapping
    • VBA Error Message
    • VBA Error Handling in a Loop
  • VBA Error Handling in Access

VBA Errors Cheat Sheet

Errors

On Error – Stop code and display error

On Error Goto 0

On Error – Skip error and continue running

On Error Resume Next

On Error – Go to a line of code [Label]

On Error Goto [Label]

Clears (Resets) Error

On Error GoTo1

Show Error number

MsgBox Err.Number

Show Description of error

MsgBox Err.Description

Function to generate own error

Err.Raise

See more VBA “Cheat Sheets” and free PDF Downloads

VBA Error Handling

VBA Error Handling refers to the process of anticipating, detecting, and resolving VBA Runtime Errors. The VBA Error Handling process occurs when writing code, before any errors actually occur.

VBA Runtime Errors are errors that occur during code execution. Examples of runtime errors include:

  • Referencing a non-existent workbook, worksheet, or other object (Run-time Error 1004)
  • Invalid data ex. referencing an Excel cell containing an error (Type Mismatch – Run-time Error 13)
  • Attempting to divide by zero

VBA On Error Statement

Most VBA error handling is done with the On Error Statement. The On Error statement tells VBA what to do if it encounters an error. There are three On Error Statements:

  • On Error GoTo 0
  • On Error Resume Next
  • On Error GoTo Line

On Error GoTo 0

On Error GoTo 0 is VBA’s default setting. You can restore this default setting by adding the following line of code:

On Error GoTo 0

When an error occurs with On Error GoTo 0, VBA will stop executing code and display its standard error message box.

vba runtime error 13

Often you will add an On Error GoTo 0 after adding On Error Resume Next error handling (next section):

Sub ErrorGoTo0()

On Error Resume Next
    ActiveSheet.Shapes("Start_Button").Delete
On Error GoTo 0

'Run More Code

End Sub

On Error Resume Next

On Error Resume Next tells VBA to skip any lines of code containing errors and proceed to the next line.

On Error Resume Next

Note: On Error Resume Next does not fix an error, or otherwise resolve it. It simply tells VBA to proceed as if the line of code containing the error did not exist. Improper use of On Error Resume Next can result in unintended consequences.

A great time to use On Error Resume Next is when working with objects that may or may not exist. For example, you want to write some code that will delete a shape, but if you run the code when the shape is already deleted, VBA will throw an error. Instead you can use On Error Resume Next to tell VBA to delete the shape if it exists.

On Error Resume Next
    ActiveSheet.Shapes("Start_Button").Delete
On Error GoTo 0

Notice we added On Error GoTo 0 after the line of code containing the potential error. This resets the error handling.

In the next section we’ll show you how to test if an error occurred using Err.Number, giving you more advanced error handling options.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Err.Number, Err.Clear, and Catching Errors

Instead of simply skipping over a line containing an error, we can catch the error by using On Error Resume Next and Err.Number.

Err.Number returns an error number corresponding with the type of error detected. If there is no error, Err.Number = 0.

For example, this procedure will return “11” because the error that occurs is Run-time error ’11’.

Sub ErrorNumber_ex()

On Error Resume Next
ActiveCell.Value = 2 / 0
MsgBox Err.Number

End Sub

vba run-time error 11 err.number

Error Handling with Err.Number

The true power of Err.Number lies in the ability to detect if an error occurred (Err.Number <> 0).  In the example below, we’ve created a function that will test if a sheet exists by using Err.Number.

Sub TestWS()
    MsgBox DoesWSExist("test")
End Sub

Function DoesWSExist(wsName As String) As Boolean
    Dim ws As Worksheet
    
    On Error Resume Next
    Set ws = Sheets(wsName)
    
    'If Error WS Does not exist
    If Err.Number <> 0 Then
        DoesWSExist = False
    Else
        DoesWSExist = True
    End If

    On Error GoTo -1
End Function

Note: We’ve added a On Error GoTo -1 to the end which resets Err.Number to 0 (see two sections down).

With On Error Resume Next and Err.Number, you can replicate the “Try” & “Catch” functionality of other programming languages.

On Error GoTo Line

On Error GoTo Line tells VBA to “go to” a labeled line of code when an error is encountered.  You declare the Go To statement like this (where errHandler is the line label to go to):

On Error GoTo errHandler

and create a line label like this:

errHandler:

Note: This is the same label that you’d use with a regular VBA GoTo Statement.

Below we will demonstrate using On Error GoTo Line to Exit a procedure.

On Error Exit Sub

You can use On Error GoTo Line to exit a sub when an error occurs.

You can do this by placing the error handler line label at the end of your procedure:

Sub ErrGoToEnd()

On Error GoTo endProc

'Some Code
    
endProc:
End Sub

or by using the Exit Sub command:

Sub ErrGoToEnd()

On Error GoTo endProc

'Some Code
GoTo skipExit
    
endProc:
Exit Sub

skipExit:

'Some More Code

End Sub

Err.Clear, On Error GoTo -1,  and Resetting Err.Number

After an error is handled, you should generally clear the error to prevent future issues with error handling.

After an error occurs, both Err.Clear and On Error GoTo -1 can be used to reset Err.Number to 0. But there is one very important difference: Err.Clear does not reset the actual error itself, it only resets the Err.Number.

What does that mean?  Using Err.Clear, you will not be able to change the error handling setting. To see the difference, test out this code and replace On Error GoTo -1 with Err.Clear:

Sub ErrExamples()

    On Error GoTo errHandler:
        
    '"Application-defined" error
    Error (13)
    
Exit Sub
errHandler:
    ' Clear Error
    On Error GoTo -1
    
    On Error GoTo errHandler2:
    
    '"Type mismatch" error
    Error (1034)
    
Exit Sub
errHandler2:
    Debug.Print Err.Description
End Sub

Typically, I recommend always using On Error GoTo -1, unless you have a good reason to use Err.Clear instead.

VBA On Error MsgBox

You might also want to display a Message Box on error.  This example will display different message boxes depending on where the error occurs:

Sub ErrorMessageEx()
 
Dim errMsg As String
On Error GoTo errHandler

    'Stage 1
    errMsg = "An error occured during the Copy & Paste stage."
    'Err.Raise (11)
    
    'Stage 2
    errMsg = "An error occured during the Data Validation stage."
    'Err.Raise (11)
     
    'Stage 3
    errMsg = "An error occured during the P&L-Building and Copy-Over stage."
    Err.Raise (11)
     
    'Stage 4
    errMsg = "An error occured while attempting to log the Import on the Setup Page"
    'Err.Raise (11)

    GoTo endProc
    
errHandler:
    MsgBox errMsg
   
endProc:
End Sub

Here you would replace Err.Raise(11) with your actual code.

VBA IsError

Another way to handle errors is to test for them with the VBA ISERROR Function. The ISERROR Function tests an expression for errors, returning TRUE or FALSE if an error occurs.

Sub IsErrorEx()
    MsgBox IsError(Range("a7").Value)
End Sub

VBA Programming | Code Generator does work for you!

If Error VBA

You can also handle errors in VBA with the Excel IFERROR Function.  The IFERROR Function must be accessed by using the WorksheetFunction Class:

Sub IfErrorEx()

Dim n As Long
n = WorksheetFunction.IfError(Range("a10").Value, 0)

MsgBox n
End Sub

This will output the value of Range A10, if the value is an error, it will output 0 instead.

VBA Error Types

Runtime Errors

As stated above:

VBA Runtime Errors are errors that occur during code execution. Examples of runtime errors include:

  • Referencing a non-existent workbook, worksheet, or other object
  • Invalid data ex. referencing an Excel cell containing an error
  • Attempting to divide by zero

vba runtime error 13

You can “error handle” runtime errors using the methods discussed above.

Syntax Errors

VBA Syntax Errors are errors with code writing. Examples of syntax errors include:

  • Mispelling
  • Missing or incorrect punctuation

The VBA Editor identifies many syntax errors with red highlighting:

vba syntax error example

The VBA Editor also has an option to “Auto Syntax Check”:

vba syntax error option

When this is checked, the VBA Editor will generate a message box alerting you syntax errors after you enter a line of code:

vba syntax compile error

I personally find this extremely annoying and disable the feature.

Compile Errors

Before attempting to run a procedure, VBA will “compile” the procedure. Compiling transforms the program from source code (that you can see) into executable form (you can’t see).

VBA Compile Errors are errors that prevent the code from compiling.

A good example of a compile error is a missing variable declaration:

vba compile error variable

Other examples include:

  • For without Next
  • Select without End Select
  • If without End If
  • Calling a procedure that does not exist

Syntax Errors (previous section) are a subset of Compile Errors.

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Debug > Compile

Compile errors will appear when you attempt to run a Procedure. But ideally, you would identify compile errors prior to attempting to run the procedure.

You can do this by compiling the project ahead of time. To do so, go to Debug > Compile VBA Project.

vba debug compile

The compiler will “go to” the first error. Once you fix that error, compile the project again. Repeat until all errors are fixed.

You can tell that all errors are fixed because Compile VBA Project will be grayed out:

vba compile vbaproject

OverFlow Error

The VBA OverFlow Error occurs when you attempt to put a value into a variable that is too large. For example, Integer Variables can only contain values between -32,768 to 32,768. If you enter a larger value, you’ll receive an Overflow error:

vba overflow error

Instead, you should use the Long Variable to store the larger number.

Other VBA Error Terms

VBA Catch Error

Unlike other programming languages, In VBA there is no Catch Statement. However, you can replicate a Catch Statement by using On Error Resume Next and If Err.Number <> 0 Then. This is covered above in Error Handling with Err.Number.

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

VBA Ignore Error

To ignore errors in VBA, simply use the On Error Resume Next statement:

On Error Resume Next

However, as mentioned above, you should be careful using this statement as it doesn’t fix an error, it just simply ignores the line of code containing the error.

VBA Throw Error / Err.Raise

To through an error in VBA, you use the Err.Raise method.

This line of code will raise Run-time error ’13’: Type mismatch:

Err.Raise (13)

vba runtime error 13

VBA Error Trapping

VBA Error Trapping is just another term for VBA Error Handling.

VBA Error Message

A VBA Error Message looks like this:

vba runtime error 13

When you click ‘Debug’, you’ll see the line of code that is throwing the error:

vba raise error

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

VBA Error Handling in a Loop

The best way to error handle within a Loop is by using On Error Resume Next along with Err.Number to detect if an error has occurred (Remember to use Err.Clear to clear the error after each occurrence).

The example below will divide two numbers (Column A by Column B) and output the result into Column C. If there’s an error, the result will be 0.

Sub test()
Dim cell As Range

On Error Resume Next
For Each cell In Range("a1:a10")

    'Set Cell Value
    cell.Offset(0, 2).Value = cell.Value / cell.Offset(0, 1).Value
    
    'If Cell.Value is Error then Default to 0
    If Err.Number <> 0 Then
         cell.Offset(0, 2).Value = 0
         Err.Clear
    End If
 Next
End Sub

VBA Error Handling in Access

All of the above examples work exactly the same in Access VBA as in Excel VBA.

Function DelRecord(frm As Form)
'this function is used to delete a record in a table from a form
   On Error GoTo ending
   With frm
      If .NewRecord Then
         .Undo
         Exit Function
      End If
   End With
   With frm.RecordsetClone
      .Bookmark = frm.Bookmark
      .Delete
      frm.Requery
   End With
   Exit Function
   ending:
   End
End Function

 

Framed

Пользователь

Сообщений: 223
Регистрация: 25.01.2018

#1

04.03.2019 19:39:20

Коллеги, приветствую,

Немного запутался в теме про обработчик ошибок, хотя, скорее всего, я нашёл ответ на вопрос в

этой теме

, просто не могу его понять до конца.

Необходимо, чтобы в случае ошибки, которая возникает в определенный момент в коде, часть кода пропускалась, появлялся MsgBox с определенным текстом, после чего макрос продолжал бы работать в нормальном режиме (если будет какая-нибудь другая ошибка далее — выскочит диалоговое окно).

Знаю, что задача простая, ну вот туплю что-то…

Код
            On Error GoTo ErrorHandler            
            Set iWb = GetObject("C:UsersA670669DesktopSCR_Managers.xlsx")
            iLastRowSCR = iWb.Sheets(1).Cells(Rows.Count, 1).End(xlUp).row
            Set iBodySCR = iWb.Sheets(1).Range("B2:M" & iLastRowSCR)
            iWb.Names.Add Name:="BodySCR", RefersTo:=iBodySCR
            With .ListColumns("Rate").DataBodyRange
                .Formula = "=IFERROR(VLOOKUP(A3,SCR_Managers.xlsx!BodySCR,12,0),0)"
                .Cells.Value = .Cells.Value
            End With
            iWb.Close False
ErrorHandler:
            MsgBox "Произошла ошибка"
            On Error Resume Next

На данный момент все как надо, только вот когда даже ошибки нет вылезает MsgBox.

Заранее спасибо.

P.S. Как-то криво написал название темы, должна была быть VBA: Обработчик ошибок, пропуск кода и продолжение выполнения макроса.

Изменено: Framed05.03.2019 00:54:10

 

Anchoret

Пользователь

Сообщений: 1065
Регистрация: 01.01.1970

Anchoret

#2

04.03.2019 19:44:33

Код
On Error Resume Next
If Err then Goto ...
 

Framed

Пользователь

Сообщений: 223
Регистрация: 25.01.2018

#3

04.03.2019 19:52:06

Anchoret, вот так?

Код
 On Error Resume Next
            MsgBox "Произошла ошибка"
            If Err Then GoTo ErrorHandler
            Set iWb = GetObject("C:UsersA670669DesktopSCR_Managers.xlsx")
            iLastRowSCR = iWb.Sheets(1).Cells(Rows.Count, 1).End(xlUp).row
            Set iBodySCR = iWb.Sheets(1).Range("B2:M" & iLastRowSCR)
            iWb.Names.Add Name:="BodySCR", RefersTo:=iBodySCR
            With .ListColumns("Rate").DataBodyRange
                .Formula = "=IFERROR(VLOOKUP(A3,SCR_Managers.xlsx!BodySCR,12,0),0)"
                .Cells.Value = .Cells.Value
            End With
            iWb.Close False
ErrorHandler:






 

Sanja

Пользователь

Сообщений: 14853
Регистрация: 10.01.2013

#4

04.03.2019 19:54:37

Цитата
Framed написал: только вот когда даже ошибки нет вылезает MsgBox

Обработчик ошибок поместите в самый конец кода, а перед ним должна быть строка Exit Sub

Код
On Error GoTo ErrorHandler
    Set iWb = GetObject("C:UsersA670669DesktopSCR_Managers.xlsx")
    iLastRowSCR = iWb.Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row
    Set iBodySCR = iWb.Sheets(1).Range("B2:M" & iLastRowSCR)
    iWb.Names.Add Name:="BodySCR", RefersTo:=iBodySCR
    With .ListColumns("Rate").DataBodyRange
        .Formula = "=IFERROR(VLOOKUP(A3,SCR_Managers.xlsx!BodySCR,12,0),0)"
        .Cells.Value = .Cells.Value
    End With
    iWb.Close False
    Exit Sub
'обработчик ошибок
ErrorHandler:
    MsgBox "Произошла ошибка"
End Sub

Согласие есть продукт при полном непротивлении сторон.

 

Framed

Пользователь

Сообщений: 223
Регистрация: 25.01.2018

#5

04.03.2019 20:03:30

Sanja, спасибо, но разве Exit Sub не остановит выполнение всего макроса, если ошибки не будет?

Я уточню, а то мне кажется, я плохо объяснил в шапке.

Код
'Код
'Код
'Код
 On Error GoTo ErrorHandler
            Set iWb = GetObject("C:UsersA670669DesktopSCR_Managers.xlsx")
            iLastRowSCR = iWb.Sheets(1).Cells(Rows.Count, 1).End(xlUp).row
            Set iBodySCR = iWb.Sheets(1).Range("B2:M" & iLastRowSCR)
            iWb.Names.Add Name:="BodySCR", RefersTo:=iBodySCR
            With .ListColumns("Rate").DataBodyRange
                .Formula = "=IFERROR(VLOOKUP(A3,SCR_Managers.xlsx!BodySCR,12,0),0)"
                .Cells.Value = .Cells.Value
            End With
            iWb.Close False
ErrorHandler:
            MsgBox "Произошла ошибка"
'Код
'Код
'Код

Выполняется макрос, и вот на 5 строке может выскочить ошибка, например, если файла нет, или его имя неверное. Мне нужно, чтобы в этом случае, часть кода 5-13 строка игнорировалась, не выполнялась и выскочил бы MsgBox c текстом, например, «Нет файла или имя некорректно». Далее код, который идет после ErrorHandler должен выполняться в обычном режиме (обычный режим для меня — это когда дальнейшие ошибки не вернут меня к ErrorHandler, простите за убогое объяснение).

В случае же, если ошибки на 5 строке моего примера не возникнет — код работает в штатном режиме.

Изменено: Framed04.03.2019 20:03:53

 

Anchoret

Пользователь

Сообщений: 1065
Регистрация: 01.01.1970

Anchoret

#6

04.03.2019 20:06:40

Framed,

Код
On Error Resume Next

перед строкой, в которой вероятна ошибка

Код
If Err then Goto ...

после такой строки. Ну и замечание от Sanja,

 

Framed

Пользователь

Сообщений: 223
Регистрация: 25.01.2018

Как-то не выходит. Дальнейшие ошибки в коде игнорируются, MsgBox вылезает, даже если ошибки не произошло.

 

БМВ

Модератор

Сообщений: 21679
Регистрация: 28.12.2016

Excel 2013, 2016

#8

04.03.2019 20:25:02

только наверно так

Код
'Код
'Код
'Код
 On Error resume next
            Set iWb = GetObject("C:UsersA670669DesktopSCR_Managers.xlsx")
            if err =0 then
                 iLastRowSCR = iWb.Sheets(1).Cells(Rows.Count, 1).End(xlUp).row
                 Set iBodySCR = iWb.Sheets(1).Range("B2:M" & iLastRowSCR)
                iWb.Names.Add Name:="BodySCR", RefersTo:=iBodySCR
                With .ListColumns("Rate").DataBodyRange
                    .Formula = "=IFERROR(VLOOKUP(A3,SCR_Managers.xlsx!BodySCR,12,0),0)"
                    .Cells.Value = .Cells.Value
                End With
                iWb.Close False
           else
                MsgBox "Произошла ошибка"
                err.clear  '  или on error goto 0
          end if
'Код
'Код
'Код
 

По вопросам из тем форума, личку не читаю.

 

Framed

Пользователь

Сообщений: 223
Регистрация: 25.01.2018

БМВ, спасибо, все отлично, только теперь в случае ошибки ниже End If, VBA продолжит выполнение кода, даже если, к примеру, название листа out of range и так далее.  

 

БМВ

Модератор

Сообщений: 21679
Регистрация: 28.12.2016

Excel 2013, 2016

Framed,  я не зря там написал ‘  или on error goto 0
В зависимости от потребностей или сбросить ошибку или и сбросить и прекратить обработку ошибок.
Конечно и через переход на метки можно сделать, но я отвык.

Изменено: БМВ04.03.2019 20:49:50

По вопросам из тем форума, личку не читаю.

 

Framed

Пользователь

Сообщений: 223
Регистрация: 25.01.2018

#11

04.03.2019 20:52:16

БМВ, простите, я проглядел. Спасибо большое за помощь, теперь я понял больше, без вас не разобрался бы.

Цитата
БМВ написал: Конечно и через переход на метки можно сделать, но я отвык.

Я где-то читал, что метки не приветствуются в VBA. Да и мне привычнее с операторами условия  :)  

 

БМВ

Модератор

Сообщений: 21679
Регистрация: 28.12.2016

Excel 2013, 2016

По вопросам из тем форума, личку не читаю.

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

#13

05.03.2019 00:23:09

Цитата
Framed написал: метки не приветствуются в VBA.

Метки не беда, если не злоупотреблять и если они не нарушаюют (

не сильно нарушают

) структуру кода

 

Nordheim

Пользователь

Сообщений: 3154
Регистрация: 18.04.2017

Причина ошибки в данном куске кода в чем заключается?

«Все гениальное просто, а все простое гениально!!!»

 

Framed

Пользователь

Сообщений: 223
Регистрация: 25.01.2018

Nordheim, потенциально ошибка в том, что файл с таким названием может отсутствовать на рабочем столе у юзера. Этот файл (если он есть) в моем коде открывается, оттуда ВПР-ом подтягивается информация, после чего он закрывается. Если такого файла нет — мне нужно было, чтобы:

1. Выводилось сообщение со специальным текстом, т.е. MsgBox;
2. Пропускался кусок кода (который открывает файл, создает именной диапазон для ВПР, подтягивает куда надо данные с этого листа с помощью ВПР, превращает формулы в значения и закрывает книгу);
3. Макрос снова бы работал в обычном режиме (то есть в режиме «on error go to 0»).

Вообще, мне помогли и тему можно было закрывать, но раз уж вы спросили :)

БМВ, да, и я даже прочитал это несколько раз перед тем, как создать тему. Просто, откровенно говоря, не доходило до меня, как это правильно использовать; примеры из гугла не добавили ясности. Одним словом, еще учиться и учиться.

Изменено: Framed05.03.2019 14:33:07

 

Nordheim

Пользователь

Сообщений: 3154
Регистрация: 18.04.2017

#16

05.03.2019 14:45:40

Цитата
Framed написал:
Nordheim , потенциально ошибка в том, что файл с таким названием может отсутствовать на рабочем столе у юзера.

А если так:

Код
Sub test()
    Dim fname$, iPath$
    iPath = "C:UsersA670669DesktopSCR_Managers.xlsx"
    fname = Dir(iPath)
    If fname <> "" Then
        'обработка если файл существует
    Else: MsgBox "Произошла ошибка"
    End If
End Sub

Никакого On Error

PS:
Обработчик ошибок это конечно хорошо, вставил в начало и никаких проблем с кодом, зато потом вылезет какая ни-будь

«бяка»

в отчетах.

Изменено: Nordheim05.03.2019 14:48:24

«Все гениальное просто, а все простое гениально!!!»

 

Jack Famous

Пользователь

Сообщений: 11140
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

#17

05.03.2019 15:02:02

Framed, очень много чего вам посоветовали — лень читать всё))
1. В большинстве случаев от меток можно абсолютно безболезненно избавится, но иногда они помогают. Например, можно избежать «ветвления» кода далеко «вправо» — вот

ссылка

на тему с холиваром)))

Итак, в чём проблема… Всё просто — код доходит до строки ErrorHandler: MsgBox «Произошла ошибка» и выводит сообщение об ошибке (как и должен). Чтобы этого избежать, я обычно делаю, как в #4 (Sanja), но можно и «в лоб» обойти:

Код
GoTo nx
            iWb.Close False
ErrorHandler:
            MsgBox "Произошла ошибка"
nx:

— в таком случае, если мы дошли до GoTo nx, то просто «перепрыгиваем» ErrorHandler на метку nx. Если же произойдёт ошибка, то макрос «перепрыгнет» уже к метке ErrorHandler, минуя GoTo nx.

P.S.:

скорее всего, в вашем случае никакого On Error GoTo ErrorHandler не нужно — это подтверждает и наличие примеров, где легко без него можно обойтись. Я использую метки в основном, если нужно вернуться «выше по коду» (повтор ввода информации пользователем в случае ошибки) или, как уже сказал, чтобы избежать «ветвления» (многоуровневых вложенных «If—Else—End If»).
Но дело (как кодить) исключительно ВАШЕ  ;)

Изменено: Jack Famous05.03.2019 15:34:40

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

БМВ

Модератор

Сообщений: 21679
Регистрация: 28.12.2016

Excel 2013, 2016

#18

05.03.2019 15:21:22

Nordheim,
тут есть подвох, я с таким встречаюсь регулярно (правда не со скриптамии, но не суть)

Код
    iPath = "C:UsersA670669DesktopГод 2019Документы раздолбая" _
          & "Результаты совещания по вопросам бездумного использования длинных имен файлов и каталогов" _
          & "Выступление главного систематизатора……SCR_Managers.xlsx"

Короче, при полном пути более 260 символов, файл есть, он виден, но открыть его не возможно, впрочем как и скопировать или удалить, понятно что лучше в этом случае обработать длину пути, но порой проще просто обратится и обработать ошибку.
Вариант 2, это уже последствия сетевого доступа к общим файлам. При переносе файлов или каталогов права не наследуются от каталога в который поместили файлы , а сохраняются прежними. Это может привести к тому что также видеть видно, а вот прочесть никак. И в этом случае без обработки ошибки не обойтись.

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

Jack Famous, так как я родом из VBS, а там нет Resume, то перешел на метку по ошибке, обратно не вернешься, что означает не продолжить с того же места. а это означает или куча меток и отдельные обработчики для каждой ошибки или …..

По вопросам из тем форума, личку не читаю.

 

Jack Famous

Пользователь

Сообщений: 11140
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

#19

05.03.2019 15:32:09

Цитата
БМВ: я родом из VBS

а я, стало быть, из VBA и могу использовать крутые штуки типа возврата наверх))

Вот такая, например

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

Nordheim

Пользователь

Сообщений: 3154
Регистрация: 18.04.2017

#20

05.03.2019 15:32:29

БМВ, На сколько я понимаю в данном случае путь прописывается руками, и визуально видно сколько символов.

Цитата
БМВ написал:
при полном пути более 260 символов, файл есть, он виден, но открыть его не возможно

Не сталкивался, потому наверное, что c Excel работаю постольку поскольку, это больше для саморазвития (интересные задания иногда встречаются).
Но теперь буду знать, а обработчиками в основном пользуюсь либо для заполнения коллекции либо в цикле где неправильный тип данных указывают и цикл не завершается пока ошибка не будет устранена.  ;)

«Все гениальное просто, а все простое гениально!!!»

 

БМВ

Модератор

Сообщений: 21679
Регистрация: 28.12.2016

Excel 2013, 2016

#21

05.03.2019 16:15:03

Цитата
Nordheim написал:
На сколько я понимаю в данном случае путь прописывается руками, и визуально видно сколько символов

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

По вопросам из тем форума, личку не читаю.

 

Казанский

Пользователь

Сообщений: 8839
Регистрация: 11.01.2013

#22

05.03.2019 16:56:51

Цитата
БМВ написал:
так как я родом из VBS, а там нет Resume, то перешел на метку по ошибке, обратно не вернешься

Забыл, забыл ты свою родину ;) Нет там меток, и GoTo только в конструкции On Error GoTo 0.

 

Framed

Пользователь

Сообщений: 223
Регистрация: 25.01.2018

Jack Famous, спасибо за разъяснения;
Nordheim, вам тоже большое спасибо, на самом деле, мне очень понравилось это решение, как и решение участника БМВ.
БМВ, спасибо за полезную информацию про ограничение.

Все-таки поясню: планируется, что файл, наличие которого проверяется, я буду высылать юзерам ежемесячно. У него относительно постоянная форма, меняются лишь данные. Соответственно, название файлу задаю тоже я. Файл носит вспомогательный характер. Вряд ли юзеры будут его переименовывать (я обязательно скажу, чтобы этого не делали) — их задача состоит лишь в том, чтобы один раз скопировать этот файл из Аутлука и куда-нибудь его закинуть, а после прописать корректный путь в VBA (а вот это им придется делать в любом случае самим, увы).

 

БМВ

Модератор

Сообщений: 21679
Регистрация: 28.12.2016

Excel 2013, 2016

#24

05.03.2019 18:47:08

Цитата
Казанский написал:
Забыл, забыл ты свою родину

:-) вооот , там даже шанса не было :-) По сему и не применяю :-)

По вопросам из тем форума, личку не читаю.

 

Nordheim

Пользователь

Сообщений: 3154
Регистрация: 18.04.2017

#25

05.03.2019 19:11:54

Цитата
Framed написал:
(а вот это им придется делать в любом случае самим, увы)

А если написать юзерам что бы сохранили файл с макросом и файл из которого берутся данные, в одну папку, то и прописывать ничего не нужно. Как вариант, можно сделать выбор файла.

«Все гениальное просто, а все простое гениально!!!»

 

RAN

Пользователь

Сообщений: 7184
Регистрация: 21.12.2012

#26

05.03.2019 19:48:22

Цитата
БМВ написал:
Короче, при полном пути более 260 символов

Еще короче. Для Exsel, кажется, 218 символов. Попадал.  :D

 

БМВ

Модератор

Сообщений: 21679
Регистрация: 28.12.2016

Excel 2013, 2016

#27

06.03.2019 08:03:50

Off

Цитата
RAN написал:
Для Exsel, кажется, 218 символов

Это не совсем про файл, а скорее про обращение к нему из самого Excel

https://support.microsoft.com/en-us/help/213983/error-message-when-you-open-or-save-a-file-in-microsoft-excel-filename

This behavior is based on a 256-character limitation in Excel for creating links to another file. This limit of 218 characters for the path name is based on the following:•Up to 31 characters in a sheet name.

•Apostrophes and brackets used to denote the workbook name.

•An exclamation point.

•A cell reference.

For example, the path for a file might resemple the following:

  ‘c:excelpersonal…[my workbook.xls]up_to_31_char_sheetname’!$A$1

Если перевести кратко, то, для работы с другой книгой, ссылка не может быть больше 256 символов, включая дополнительные символы (скобки,апострофы, восклицательный знак), имя листа  и диапазон.   если учесть что  Адрес может быть $AAA$1000000 (12 сим) +31 на имя листа + 5 на спец символы, то на путь останется менее 218ти
256-12-31-5=208

По вопросам из тем форума, личку не читаю.

 

Nordheim

Пользователь

Сообщений: 3154
Регистрация: 18.04.2017

#28

06.03.2019 08:54:26

В дополнении  

Цитата
Nordheim написал:
А если написать юзерам что бы сохранили файл с макросом и файл из которого берутся данные, в одну папку

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

Прикрепленные файлы

  • Книга1.xlsm (16.3 КБ)

«Все гениальное просто, а все простое гениально!!!»

 

Framed

Пользователь

Сообщений: 223
Регистрация: 25.01.2018

#29

13.03.2019 17:36:49

Коллеги, прошу прощения заранее, что поднимаю старую тему и задаю в ней вопрос, но он связан с тем же макросом и с тем, что мне ответил пользователь Nordheim.

Цитата
Nordheim написал:
А если написать юзерам что бы сохранили файл с макросом

Файлы не с макросом, потому что модуль с ним находится в личной книге макросов.

Цитата
Nordheim написал:
Как вариант, можно сделать выбор файла.

Вот тут я хотел бы уточнить, если вы не против. Можно ли сделать такой алгоритм (но я точно не знаю, в самом макросе, или сделать отдельный), который поможет юзеру выбрать вспомогательный файл (как с сохранением, с помощью окна), а основной макрос бы ссылался на выбранный файл.

Зачем это нужно: планируются, что такие вспомогательные файлы будут отправляться юзерам раз в месяц, соответственно, можно их просто назвать одним именем и заменять один другим (как и реализованно в данный момент), но было бы лучше, если бы они сохранялись в специально созданной для этого папке, а юзеры могли бы просто «переключаться» между файлами, из которых нужно брать инфу.  

 

Jack Famous

Пользователь

Сообщений: 11140
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

#30

13.03.2019 18:02:32

Framed, если вопрос не связан с темой (Обработчик ошибок, пропуск куска кода), то создавайте новую

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

In a VBA code, there may be some errors like syntax errors, compilation errors, or runtime errors so we need to handle these errors. Suppose there is a code of 200 lines and the code has an error it’s very difficult to find an error in the code of 200 lines so it’s better to handle the error where we are expecting some error in our code. There are many errors handling methods in VBA which we will discuss in this article but before that, we will discuss types of error.

VBA Errors

Syntax Error

This error will occur if any syntax is not correctly written in the code then VBA will display an error message.

Syntax-error-occurred

Examples of Syntax Error

Example-of-syntax-error

Compilation Error

When there is a statement where there is an error in more than one line of its statement then VBA will display an error message. In the following example, a for loop is written without Next which is a compilation error

Compilation-error-occurred

Runtime Error

A code that is written perfectly but an error occurs at the time of execution. For example, if a file address is attached to the code which doesn’t exist or when a number is divided by zero a case runtime error occurs.

Runtime-error-occurred

Logical Error

The compiler can not highlight the logical errors but it will give a wrong output. The code will run without any error but the output will come wrong. In case of a large number of codes, it is difficult to identify the logical errors we need to press “F8” it will run the code one line at a time and we can identify the mistakes for which we are getting the wrong output. The following code is written to the difference between two numbers where we are getting the summation of two numbers.

Logical-error-found

Here, we can identify our logical error that instead of “-” we have written “+”

Expected Vs Unexpected Errors

  • Expected Errors: Where we are expecting to get an error, there we write our own code to handle the error.
  • Unexpected Errors: Where we don’t need to write our own code we have VBA error handling statements to handle the errors

Types of Error Handling Statements

On Error

It is used to handle errors that occur during run time.

  • On Error GoTo 0: This statement will show an error message that a number or a variable is divided by zero.

Error-occurred-due-to-division-by-0

  • On Error Resume Next: It tells VBA if it gets a run time error then don’t show the error message simply resume to the next statement.

Not-showing-error

  • On Error GoTo [label]: If it gets an error then it will go to the specific statement which we will mention in the “label” part.

Error-mentioned-in-label

The Err Object

When an error occurs an err object is created with help of that we can get the type of error and error number.

Err-object-created

The Er1 Function 

It is used to get the line number of the error.

er1-function

Err.Raise

We can create our own errors with the help of this method.

Syntax: Err. Raise [Number of the error],[Source of the error], [Description of the error]

From 1-512, number of errors is reserved by VBA. So, we can use anything from 513 to 65535.

Err.Clear

It is used to clear the number and type of the error from the Err.Object.

Error Function

It is used to print the description of the error from its number.

Printing-description-of-error

Last Updated :
16 Nov, 2022

Like Article

Save Article

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

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

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

Обработчик ошибок позволяет завершить выполнение программы при возникновении ошибки и вывести сообщение пользователю с ее описанием.

Синтаксис выражений с On Error

Включает алгоритм обнаружения ошибок и, в случае возникновения ошибки, передает управление операторам обработчика ошибок с указанной в выражении строки. Stroka – это метка, после которой расположены операторы обработчика ошибок.

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

Отключает любой включенный обработчик ошибок в текущей процедуре.

Простой обработчик ошибок

Шаблон простейшего обработчика ошибок:

Sub Primer()

On Error GoTo Stroka

    ‘Блок операторов процедуры

Exit Sub

Stroka:

    MsgBox «Произошла ошибка: « & Err.Description

End Sub

Оператор On Error GoTo размещается в начале процедуры, метка и обработчик ошибок – в конце процедуры. Название метки можно сменить на другое, в том числе на кириллице.

Оператор Exit Sub обеспечивает выход из процедуры, если блок операторов выполнен без ошибок. Для вывода описания ошибки используется свойство Description объекта Err.

Примеры обработки ошибок

Пример 1
Деление на ноль:

Sub Primer1()

On Error GoTo Инструкция

    Dim a As Double

    a = 45 / 0

Exit Sub

Instr:

    MsgBox «Произошла ошибка: « & Err.Description

End Sub

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

Пример 2
Выход за границы диапазона:

Sub Primer2()

On Error GoTo Instr

    Dim myRange As Range

    Set myRange = Range(«A1:D4»).Offset(2)

Exit Sub

Instr:

    MsgBox «Произошла ошибка: « & Err.Description

End Sub

Результат выполнения кода VBA Excel с оператором On Error GoTo:

Пример использования выражений On Error Resume Next и On Error GoTo 0 смотрите в статье: Отбор уникальных значений с помощью Collection.

In this Article

  • VBA Errors Cheat Sheet
    • Errors
  • VBA Error Handling
  • VBA On Error Statement
    • On Error GoTo 0
    • On Error Resume Next
    • Err.Number, Err.Clear, and Catching Errors
    • On Error GoTo Line
  • VBA IsError
  • If Error VBA
  • VBA Error Types
    • Runtime Errors
    • Syntax Errors
    • Compile Errors
    • Debug > Compile
    • OverFlow Error
  • Other VBA Error Terms
    • VBA Catch Error
    • VBA Ignore Error
    • VBA Throw Error / Err.Raise
    • VBA Error Trapping
    • VBA Error Message
    • VBA Error Handling in a Loop
  • VBA Error Handling in Access

VBA Errors Cheat Sheet

Errors

On Error – Stop code and display error

On Error Goto 0

On Error – Skip error and continue running

On Error Resume Next

On Error – Go to a line of code [Label]

On Error Goto [Label]

Clears (Resets) Error

On Error GoTo1

Show Error number

MsgBox Err.Number

Show Description of error

MsgBox Err.Description

Function to generate own error

Err.Raise

See more VBA “Cheat Sheets” and free PDF Downloads

VBA Error Handling

VBA Error Handling refers to the process of anticipating, detecting, and resolving VBA Runtime Errors. The VBA Error Handling process occurs when writing code, before any errors actually occur.

VBA Runtime Errors are errors that occur during code execution. Examples of runtime errors include:

  • Referencing a non-existent workbook, worksheet, or other object (Run-time Error 1004)
  • Invalid data ex. referencing an Excel cell containing an error (Type Mismatch – Run-time Error 13)
  • Attempting to divide by zero

VBA On Error Statement

Most VBA error handling is done with the On Error Statement. The On Error statement tells VBA what to do if it encounters an error. There are three On Error Statements:

  • On Error GoTo 0
  • On Error Resume Next
  • On Error GoTo Line

On Error GoTo 0

On Error GoTo 0 is VBA’s default setting. You can restore this default setting by adding the following line of code:

On Error GoTo 0

When an error occurs with On Error GoTo 0, VBA will stop executing code and display its standard error message box.

vba runtime error 13

Often you will add an On Error GoTo 0 after adding On Error Resume Next error handling (next section):

Sub ErrorGoTo0()

On Error Resume Next
    ActiveSheet.Shapes("Start_Button").Delete
On Error GoTo 0

'Run More Code

End Sub

On Error Resume Next

On Error Resume Next tells VBA to skip any lines of code containing errors and proceed to the next line.

On Error Resume Next

Note: On Error Resume Next does not fix an error, or otherwise resolve it. It simply tells VBA to proceed as if the line of code containing the error did not exist. Improper use of On Error Resume Next can result in unintended consequences.

A great time to use On Error Resume Next is when working with objects that may or may not exist. For example, you want to write some code that will delete a shape, but if you run the code when the shape is already deleted, VBA will throw an error. Instead you can use On Error Resume Next to tell VBA to delete the shape if it exists.

On Error Resume Next
    ActiveSheet.Shapes("Start_Button").Delete
On Error GoTo 0

Notice we added On Error GoTo 0 after the line of code containing the potential error. This resets the error handling.

In the next section we’ll show you how to test if an error occurred using Err.Number, giving you more advanced error handling options.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Err.Number, Err.Clear, and Catching Errors

Instead of simply skipping over a line containing an error, we can catch the error by using On Error Resume Next and Err.Number.

Err.Number returns an error number corresponding with the type of error detected. If there is no error, Err.Number = 0.

For example, this procedure will return “11” because the error that occurs is Run-time error ’11’.

Sub ErrorNumber_ex()

On Error Resume Next
ActiveCell.Value = 2 / 0
MsgBox Err.Number

End Sub

vba run-time error 11 err.number

Error Handling with Err.Number

The true power of Err.Number lies in the ability to detect if an error occurred (Err.Number <> 0).  In the example below, we’ve created a function that will test if a sheet exists by using Err.Number.

Sub TestWS()
    MsgBox DoesWSExist("test")
End Sub

Function DoesWSExist(wsName As String) As Boolean
    Dim ws As Worksheet
    
    On Error Resume Next
    Set ws = Sheets(wsName)
    
    'If Error WS Does not exist
    If Err.Number <> 0 Then
        DoesWSExist = False
    Else
        DoesWSExist = True
    End If

    On Error GoTo -1
End Function

Note: We’ve added a On Error GoTo -1 to the end which resets Err.Number to 0 (see two sections down).

With On Error Resume Next and Err.Number, you can replicate the “Try” & “Catch” functionality of other programming languages.

On Error GoTo Line

On Error GoTo Line tells VBA to “go to” a labeled line of code when an error is encountered.  You declare the Go To statement like this (where errHandler is the line label to go to):

On Error GoTo errHandler

and create a line label like this:

errHandler:

Note: This is the same label that you’d use with a regular VBA GoTo Statement.

Below we will demonstrate using On Error GoTo Line to Exit a procedure.

On Error Exit Sub

You can use On Error GoTo Line to exit a sub when an error occurs.

You can do this by placing the error handler line label at the end of your procedure:

Sub ErrGoToEnd()

On Error GoTo endProc

'Some Code
    
endProc:
End Sub

or by using the Exit Sub command:

Sub ErrGoToEnd()

On Error GoTo endProc

'Some Code
GoTo skipExit
    
endProc:
Exit Sub

skipExit:

'Some More Code

End Sub

Err.Clear, On Error GoTo -1,  and Resetting Err.Number

After an error is handled, you should generally clear the error to prevent future issues with error handling.

After an error occurs, both Err.Clear and On Error GoTo -1 can be used to reset Err.Number to 0. But there is one very important difference: Err.Clear does not reset the actual error itself, it only resets the Err.Number.

What does that mean?  Using Err.Clear, you will not be able to change the error handling setting. To see the difference, test out this code and replace On Error GoTo -1 with Err.Clear:

Sub ErrExamples()

    On Error GoTo errHandler:
        
    '"Application-defined" error
    Error (13)
    
Exit Sub
errHandler:
    ' Clear Error
    On Error GoTo -1
    
    On Error GoTo errHandler2:
    
    '"Type mismatch" error
    Error (1034)
    
Exit Sub
errHandler2:
    Debug.Print Err.Description
End Sub

Typically, I recommend always using On Error GoTo -1, unless you have a good reason to use Err.Clear instead.

VBA On Error MsgBox

You might also want to display a Message Box on error.  This example will display different message boxes depending on where the error occurs:

Sub ErrorMessageEx()
 
Dim errMsg As String
On Error GoTo errHandler

    'Stage 1
    errMsg = "An error occured during the Copy & Paste stage."
    'Err.Raise (11)
    
    'Stage 2
    errMsg = "An error occured during the Data Validation stage."
    'Err.Raise (11)
     
    'Stage 3
    errMsg = "An error occured during the P&L-Building and Copy-Over stage."
    Err.Raise (11)
     
    'Stage 4
    errMsg = "An error occured while attempting to log the Import on the Setup Page"
    'Err.Raise (11)

    GoTo endProc
    
errHandler:
    MsgBox errMsg
   
endProc:
End Sub

Here you would replace Err.Raise(11) with your actual code.

VBA IsError

Another way to handle errors is to test for them with the VBA ISERROR Function. The ISERROR Function tests an expression for errors, returning TRUE or FALSE if an error occurs.

Sub IsErrorEx()
    MsgBox IsError(Range("a7").Value)
End Sub

VBA Programming | Code Generator does work for you!

If Error VBA

You can also handle errors in VBA with the Excel IFERROR Function.  The IFERROR Function must be accessed by using the WorksheetFunction Class:

Sub IfErrorEx()

Dim n As Long
n = WorksheetFunction.IfError(Range("a10").Value, 0)

MsgBox n
End Sub

This will output the value of Range A10, if the value is an error, it will output 0 instead.

VBA Error Types

Runtime Errors

As stated above:

VBA Runtime Errors are errors that occur during code execution. Examples of runtime errors include:

  • Referencing a non-existent workbook, worksheet, or other object
  • Invalid data ex. referencing an Excel cell containing an error
  • Attempting to divide by zero

vba runtime error 13

You can “error handle” runtime errors using the methods discussed above.

Syntax Errors

VBA Syntax Errors are errors with code writing. Examples of syntax errors include:

  • Mispelling
  • Missing or incorrect punctuation

The VBA Editor identifies many syntax errors with red highlighting:

vba syntax error example

The VBA Editor also has an option to “Auto Syntax Check”:

vba syntax error option

When this is checked, the VBA Editor will generate a message box alerting you syntax errors after you enter a line of code:

vba syntax compile error

I personally find this extremely annoying and disable the feature.

Compile Errors

Before attempting to run a procedure, VBA will “compile” the procedure. Compiling transforms the program from source code (that you can see) into executable form (you can’t see).

VBA Compile Errors are errors that prevent the code from compiling.

A good example of a compile error is a missing variable declaration:

vba compile error variable

Other examples include:

  • For without Next
  • Select without End Select
  • If without End If
  • Calling a procedure that does not exist

Syntax Errors (previous section) are a subset of Compile Errors.

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Debug > Compile

Compile errors will appear when you attempt to run a Procedure. But ideally, you would identify compile errors prior to attempting to run the procedure.

You can do this by compiling the project ahead of time. To do so, go to Debug > Compile VBA Project.

vba debug compile

The compiler will “go to” the first error. Once you fix that error, compile the project again. Repeat until all errors are fixed.

You can tell that all errors are fixed because Compile VBA Project will be grayed out:

vba compile vbaproject

OverFlow Error

The VBA OverFlow Error occurs when you attempt to put a value into a variable that is too large. For example, Integer Variables can only contain values between -32,768 to 32,768. If you enter a larger value, you’ll receive an Overflow error:

vba overflow error

Instead, you should use the Long Variable to store the larger number.

Other VBA Error Terms

VBA Catch Error

Unlike other programming languages, In VBA there is no Catch Statement. However, you can replicate a Catch Statement by using On Error Resume Next and If Err.Number <> 0 Then. This is covered above in Error Handling with Err.Number.

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

VBA Ignore Error

To ignore errors in VBA, simply use the On Error Resume Next statement:

On Error Resume Next

However, as mentioned above, you should be careful using this statement as it doesn’t fix an error, it just simply ignores the line of code containing the error.

VBA Throw Error / Err.Raise

To through an error in VBA, you use the Err.Raise method.

This line of code will raise Run-time error ’13’: Type mismatch:

Err.Raise (13)

vba runtime error 13

VBA Error Trapping

VBA Error Trapping is just another term for VBA Error Handling.

VBA Error Message

A VBA Error Message looks like this:

vba runtime error 13

When you click ‘Debug’, you’ll see the line of code that is throwing the error:

vba raise error

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

VBA Error Handling in a Loop

The best way to error handle within a Loop is by using On Error Resume Next along with Err.Number to detect if an error has occurred (Remember to use Err.Clear to clear the error after each occurrence).

The example below will divide two numbers (Column A by Column B) and output the result into Column C. If there’s an error, the result will be 0.

Sub test()
Dim cell As Range

On Error Resume Next
For Each cell In Range("a1:a10")

    'Set Cell Value
    cell.Offset(0, 2).Value = cell.Value / cell.Offset(0, 1).Value
    
    'If Cell.Value is Error then Default to 0
    If Err.Number <> 0 Then
         cell.Offset(0, 2).Value = 0
         Err.Clear
    End If
 Next
End Sub

VBA Error Handling in Access

All of the above examples work exactly the same in Access VBA as in Excel VBA.

Function DelRecord(frm As Form)
'this function is used to delete a record in a table from a form
   On Error GoTo ending
   With frm
      If .NewRecord Then
         .Undo
         Exit Function
      End If
   End With
   With frm.RecordsetClone
      .Bookmark = frm.Bookmark
      .Delete
      frm.Requery
   End With
   Exit Function
   ending:
   End
End Function

If VBA can’t execute a statement (command) then a run-time error occurs. By default Excel deals with these, so when a run-time error occurs, you’ll see a default error message like this:

vba runtime error

But you can change this and instruct Excel to allow your code to deal with run-time errors.

NOTE : I’m going to use the terms sub, function and procedure interchangeably. For the purposes of this article they all mean the same thing – a chunk of code written to do a particular thing.

The On Error Statement

To instruct Excel what to do when an error occurs, you use the On Error statement. You can use On Error in four ways:

On Error GoTo 0
On Error Resume Next
On Error GoTo [label]
On Error GoTo -1 

On Error GoTo 0

This is the default mode and is already turned on when you start writing your code. You don’t need to use an On Error GoTo 0 statement at the start of your VBA.

In this mode VBA displays the standard style error message box, and gives you the choice to Debug the code (enter VBA editor and use debugging tools) or End code execution.

You would use On Error GoTo 0 to turn default error handling back on if you have previously told VBA to deal with errors in some other way e.g. by using On Error Resume Next.

On Error Resume Next

On Error Resume Next tells VBA to continue executing statements immediately after the statement that generated the error.

On Error Resume Next allows your code to continue running even if an error occurs. Resume Next does not fix an error, it just ignores it. This can be good and bad.

The Good?

If you know that your code could generate an error, then using Resume Next can prevent an interruption in code execution.

For example, we want to create a file, but I want to make sure a file with the same name doesn’t already exist. To do this, I will attempt to delete the file, and of course if it doesn’t already exist, an error will occur.

I don’t care if an error occurs. If it does, the file doesn’t exist and that’s fine for what I want to do. So before I attempt to delete the file, I instruct VBA to ignore the error.

Sub DeleteFile()
    
    Dim FilePath As String
    
    FilePath = "d:tempsomefile.csv"
    
    On Error Resume Next
    
    'Delete the file
    Kill FilePath
    
    'If the file doesn't exist the Kill statement
    'generates an error.
    'But I have assumed that is ok as it indicates that
    'I am ok to create a new file with the same filename
    'This is a bad assumption - see the next sub 
    'UnhandledError()

End Sub

The Bad

But hang on. What if the file I am trying to delete is read only? If it is I will get an error when I try to delete it. I’ve assumed that I will only get an error if the file isn’t there. So an error caused by trying to delete a read only file will get missed.

And If I then try to create a new file with the same name, or open it for writing data to it, I will generate more errors and they will be missed too.

Sub UnhandledError()

    Dim FilePath As String
    
    FilePath = "d:tempsomefile.csv"
    
    On Error Resume Next
    
    'Delete the file
    Kill FilePath
    
    'But if the file is read-only I can't delete it
    'and the Kill statement generates an error
    'I can't now create a new file with the same name
    
    'Trying to Open the file for writing data to it will
    'also generate an error but it will be missed as
    'we've told VBA to continue executing code if an
    'error occurs
    Open FilePath For Output As #1
    Write #1, "Some data"
    Close #1

End Sub

If you do use On Error Resume Next you should immediately turn default error handling back on (or turn on your custom error handler – see below)

Be careful when using On Error Resume Next. You are better off seeing if an error occurred by checking the Err object (see below). Doing this can tell you the error number and help you figure out exactly what happened.

On Error GoTo [LABEL]

If an error occurs, this transfers code execution to the line following the label. This is typically used to specify your own error handling code.

None of the code between the line generating the error and the label is executed.

Error Handlers

So you write your own error handling code and use On Error GoTo [LABEL] to instruct VBA to use your code to deal with errors.

You can place your error-handling code anywhere in a procedure, but typically it is placed at the end.

Your error handler should either fix the error and resume code execution, or terminate the routine gracefully.

Sub ErrorHandler()

    Dim num As Integer

    On Error GoTo ErrHandler

    num = 1 / 0
    
    MsgBox "This line is not executed"

Exit sub


ErrHandler:

    MsgBox "Oops, an error has occured." & vbCrLf & vbCrLf & "Error Code : " & Err.Number & " , " & Err.Description

End Sub

As VBA will execute each line of code in turn going from top to bottom, if no error is generated then it will execute your error handling code when it gets to that point in your sub.

To prevent this happening, use an Exit Sub, Exit Function, or Exit Property statement before your error handling routine.

In the example above, if the value assigned to num was valid e.g. num = 1/1, then we don’t want the code beneath ErrHandler: executed. So just before the ErrHandler: label, I’ve used an Exit Sub statement.

Multiple Error Handlers

You can have more than one error handler in a routine, but only one of them can be active at any time.

You could have something like:

Sub MultipleErrorHandlers()
	On Error GoTo ErrHandler1
	[some code]

	On Error GoTo ErrHandler2
	[some code]

	Exit Sub

ErrHandler1:
	[ErrHandler1 Code]
	Exit Sub

ErrHandler2:
	[ErrHandler1 Code]
	Exit Sub
End Sub

If an error occurs between On Error GoTo ErrHandler1 and On Error GoTo ErrHandler2 then the ErrHandler1 code is executed.

If an error occurs after On Error GoTo ErrHandler2 then the ErrHandler2 code is executed.

NOTE: Notice that at the end of each error handling routine is an Exit Sub statement. If I didn’t use these, when the ErrHandler1 code is finished executing, VBA could just continue on down to the next line and execute the ErrHandler2 code as well.

Strictly speaking I don’t need the Exit Sub at the end of the ErrHandler2 code, as it is the last line in the sub, but it is a good habit to get into.

Err object

When an error occurs the Err object contains information about the error like the error number and a description of the error.

As any given line of code can generate multiple errors it’s a good idea to examine the Err object to determine what you want to do in your code.

Err.Number gives you the error number, and Err.Description gives you a description of the error.

Sub CheckErrObject()
    
    Dim FilePath As String
    
    FilePath = "d:tempsomefile.csv"
    
    On Error GoTo ErrHandler
    
    'Delete the file
    Kill FilePath
    
    Open FilePath For Output As #1
    Write #1, "Some data"
    Close #1

    
    Exit Sub
    

ErrHandler:
    
    Select Case Err.Number
      
        Case 53   ' File doesn't exist
            Err.Clear ' Clear the error
      
        Case 75   ' File is Read Only
            MsgBox "Error Number : " & Err.Number & vbCrLf & vbCrLf & Err.Description
            Exit Sub
      
      Case Else
         ' Code to handle other errors
         
   End Select
   
   Resume Next ' Continue executing code after line that generated error
   
End Sub

Resume

The Resume statement tells VBA to resume executing code at a specified point. Resume can only be used in an error handling routine, any other use will generate an error.

Resume takes three forms:

Resume
Resume Next
Resume [label]

Using just Resume causes execution to resume at the same line of code that caused the error. If you haven’t fixed the error, your code will begin an infinite loop as it switches between the line of code generating the error and the error handling routine.

If you look at the example sub Resume_Next() which is below, num = 1 / 0 causes a Divide by 0 error. I’ve instructed VBA to use my error handler, called ErrHandler.

In ErrHandler I’ve attempted to fix the error by assigning num the value 1. If I then used only Resume, all that would happen is that VBA would go back to num = 1 / 0 and another Divide by 0 error would be generated.

Instead, I use Resume Next to carry on executing code at the line after the one causing the error.

In doing so I have handled the error by assigning the value 1 to num, and execution will continue without another error at the line result = num / 1

Sub Resume_Next()

    Dim num As Integer
    Dim result As Integer

    On Error GoTo ErrHandler

    num = 1 / 0
    result = num  / 1
    
    Exit Sub

ErrHandler:   
    num = 1
    Resume Next
   
End Sub

Resume [label] passes code execution to the line with that label.

Sub Resume_Next()

    Dim num As Integer
    Dim result As Integer

    On Error GoTo ErrHandler

    num = 1 / 0
    result = num  / 1

MyLabel:

‘Code execution starts again from here
result = num * 1

    Exit Sub

ErrHandler:   
    num = 1
    Resume MyLabel
   
End Sub

Whenever you use Resume it clears the Err object.

Error Handling With Multiple Procedures

Every sub/function doesn’t have to have an error handler. If an error occurs, VBA will use the last On Error statement to determine what happens.

If an On Error statement has been used in a procedure and an error occurs in that procedure, then that error is handled as I’ve just described.

But if an error occurs in a sub that hasn’t used an On Error statement, VBA goes back through procedure calls until it finds an On Error directive.

Let’s look at an example with three subs.

SubOne() calls SubTwo(). SubTwo calls SubThree(), and has some code of its own to execute. SubThree() carries out a calculation.

Sub SubOne()

    On Error GoTo ErrHandler
    
    SubTwo

    Exit Sub
    
ErrHandler:
    
    MsgBox "Error caught in SubOne"
    
End Sub

Sub SubTwo()

    SubThree
    
    MsgBox "No errors here"
    
End Sub

Sub SubThree()

    Dim num As Integer
    
    num = 1 / 0
    
End Sub

SubOne() has an error handler routine, ErrHandler, and has instructed VBA to use it.

SubTwo() will display a message on screen after it’s call to SubThree() has finished.

However SubThree() generates a Divide by 0 error.

SubThree() hasn’t used an On Error statement to tell VBA what to do if an error occurs, so VBA goes back to SubTwo(). That also doesn’t have an On Error statement so VBA goes back to SubOne().

Here we have our error handler and the code in it is executed.

Note that the message «No errors here» in SubTwo() is not displayed because that line of code is not executed.

When SubThree() generated an error, code execution went back to the error handler in SubOne() and any code in SubTwo() after the call to SubThree() is missed out.

On Error GoTo -1

This resets the current error. It’s the equivalent of using Err.Clear.

You can see that in this sub, after the Divide By 0 error is generated, after On Error GoTo -1 is used, Err.Number is 0 (no error) and Err.Description is empty.

Sub GoToMinus1()

    Dim num As Integer

    On Error Resume Next

    num = 1 / 0

    'If error is Divide by Zero
    If Err.Number = 11 Then

        MsgBox "Error Code : " & Err.Number & " , " & Err.Description
        On Error GoTo -1
        MsgBox "Error Code : " & Err.Number & " , " & Err.Description
    
    End If

End Sub

Sample Code

Enter your email address below to download the sample workbook.

By submitting your email address you agree that we can email you our Excel newsletter.

  • Макрос excel если ошибка
  • Макнамара путем ошибок к катастрофе скачать
  • Макияж для нависшего века ошибки
  • Макияж для глаз ошибки
  • Макита фен выдает ошибку