Vba как отключить сообщения об ошибках

title description ms.date ms.topic helpviewer_keywords ms.assetid author ms.author manager ms.technology ms.workload

Configuring Warnings in Visual Basic

Learn about how you can configure warnings in Visual Basic which, in turn, will help you write cleaner, faster, better code with fewer bugs.

11/04/2016

conceptual

errors [Visual Basic], warnings

run-time errors, warnings

warnings, configuring

99cf4781-bd4d-47b4-91b9-217933509f82

ghogen

ghogen

jmartens

vs-ide-general

multiple

Configuring warnings in Visual Basic

[!INCLUDE Visual Studio]

The [!INCLUDEvbprvb] compiler includes a set of warnings about code that may cause run-time errors. You can use that information to write cleaner, faster, better code with fewer bugs. For example, the compiler will produce a warning when the user attempts to invoke a member of an unassigned object variable, return from a function without setting the return value, or execute a Try block with errors in the logic to catch exceptions.

Sometimes the compiler provides extra logic on the user’s behalf so that the user can focus on the task at hand, rather than on anticipating possible errors. In previous versions of [!INCLUDEvbprvb], Option Strict was used to limit the additional logic that the [!INCLUDEvbprvb] compiler provides. Configuring warnings allows you to limit this logic in a more granular way, at the level of the individual warnings.

You may want to customize your project and turn off some warnings not pertinent to your application while turning other warnings into errors. This page explains how to turn individual warnings on and off.

Turning warnings off and on

There are two different ways to configure warnings: you can configure them using the Project Designer, or you can use the /warnaserror and /nowarn compiler options.

The Compile tab of the Project Designer page allows you to turn warnings on and off. Select the Disable All Warnings check box to disable all warnings; select the Treat All Warnings as Errors to treat all warnings as errors. Some individual warnings can be toggled as error or warning as desired in the displayed table.

When Option Strict is set to Off, Option Strict related warnings cannot be treated independently of each other. When Option Strict is set to On, the associated warnings are treated as errors, no matter what their status is. When Option Strict is set to Custom by specifying /optionstrict:custom in the command line compiler, Option Strict warnings can be toggled on or off independently.

The /warnaserror command-line option of the compiler can also be used to specify whether warnings are treated as errors. You can add a comma delimited list to this option to specify which warnings should be treated as errors or warnings by using + or -. The following table details the possible options.

Command-line option Specifies
/warnaserror+ Treat all warnings as errors
/warnsaserror Do not treat as warnings as errors. This is the default.
/warnaserror+:<warning list > Treat specific warnings as errors, listed by their error ID number in a comma delimited list r.
/warnaserror-:<warning list> Do not treat specific warnings as errors, listed by their error ID number in a comma delimited list.
/nowarn Do not report warnings.
/nowarn:<warning list> Do not report specified warnings, listed by their error ID number in a comma delimited list.

The warning list contains the error ID numbers of the warnings that should be treated as errors, which can be used with the command-line options to turn specific warnings on or off. If the warning list contains an invalid number, an error is reported.

Examples

This table of examples of command line arguments describes what each argument does.

Argument Description
vbc /warnaserror Specifies that all warnings should be treated as errors.
vbc /warnaserror:42024 Specifies that warning 42024 should be treated as an error.
vbc /warnaserror:42024,42025 Specifies that warnings 42024 and 42025 should be treated as errors.
vbc /nowarn Specifies that no warnings should be reported.
vbc /nowarn:42024 Specifies that warning 42024 should not be reported.
vbc /nowarn:42024,42025 Specifies that warnings 42024 and 42025 should not be reported.

Types of warnings

Following is a list of warnings that you might want to treat as errors.

Implicit conversion warning

Generated for instances of implicit conversion. They do not include implicit conversions from an intrinsic numeric type to a string when using the & operator. Default for new projects is off.

ID: 42016

Late bound method invocation and overload resolution warning

Generated for instances of late binding. Default for new projects is off.

ID: 42017

Operands of type ‘Object’ warnings

Generated when operands of type Object occur that would create an error with Option Strict On. Default for new projects is on.

ID: 42018 and 42019

Declarations require ‘As’ clause warnings

Generated when a variable, function, or property declaration lacking an As clause would have created an error with Option Strict On. Variables that do not have a type assigned to them are assumed to be type Object. Default for new projects is on.

ID: 42020 (variable declaration), 42021 (function declaration), and 42022 (property declaration).

Possible null reference exception warnings

Generated when a variable is used before it has been assigned a value. Default for new projects is on.

ID: 42104, 42030

Unused local variable warning

Generated when a local variable is declared but never referred to. Default is on.

ID: 42024

Access of shared member through instance variable warning

Generated when accessing a shared member through an instance may have side effects, or when accessing a shared member through an instance variable is not the right-hand side of an expression or is being passed in as a parameter. Default for new projects is on.

ID: 42025

Recursive operator or property access warnings

Generated when the body of a routine uses the same operator or property it is defined in. Default for new projects is on.

ID: 42004 (operator), 42026 (property)

Function or operator without return value warning

Generated when the function or operator does not have a return value specified. This includes omitting a Set to the implicit local variable with the same name as the function. Default for new projects is on.

ID: 42105 (function), 42016 (operator)

Overloads modifier used in a module warning

Generated when Overloads is used in a Module. Default for new projects is on.

ID: 42028

Duplicate or overlapping catch blocks warnings

Generated when a Catch block is never reached due to its relation to other Catch blocks that have been defined. Default for new projects is on.

ID: 42029, 42031

See also

  • Error types
  • Try…Catch…Finally statement
  • /nowarn
  • /warnaserror (Visual Basic)
  • Compile page, Project Designer (Visual Basic)
  • Compiler warnings that are off by default

When you’re editing a Microsoft Office VBA macro or function, you will often move your cursor from a line that you haven’t finished. For example, to go copy something you want to paste into that line. But, if that partial line isn’t syntactically valid, the VBA editor interrupts your work by popping up a «Compile error» message that has to be dismissed.

Is there any way to disable the message box? I find it irritating…

(This happens with Excel Visual Basic for Applications, Outlook VBA, Word VBA, etc.)

Jon Freed's user avatar

asked Jul 19, 2012 at 12:29

Iain S's user avatar

1

Do the following in your VBA editor window (entitled «Microsoft Visual Basic for Applications»):

Click the menu «Tools» and then «Options«.

In the Options’ «Editor» tab, uncheck the «Auto Syntax Check» box. (See screenshot, below.)

This change does not make the editor stop compiling in the background and marking syntax errors in red (or whatever formatting is specified in the Options tab «Editor Format»).

MS Office programs share this common VBA editor, so if you change an option while editing VBA for Excel then you’ve changed it for Outlook, Word, etc.

MS VBA editor's Tools Options dialog box

Jon Freed's user avatar

answered Jul 19, 2012 at 13:29

ray's user avatar

rayray

8,5017 gold badges44 silver badges58 bronze badges

8

In the VBE, Tools — Options — Editor and uncheck Auto Syntax Check. It will turn bad code red, but won’t give you the popup.

answered Jul 19, 2012 at 13:30

Dick Kusleika's user avatar

Dick KusleikaDick Kusleika

32.6k4 gold badges51 silver badges73 bronze badges

By Chris Newman •  Updated: 02/13/14 • 
2 min read

Turn Off Syntax/Compile Error Alerts in Visual Basic Editor

Writing VBA Code Can’t Be This Annoying, Can It?

When I first started coding in the Visual Basic Editor (VBE) I would always get so annoyed with the message box alerts that would pop up every time I didn’t use proper code syntax.  This caused me to get distracted since every time I didn’t type something in properly I would get an error alert and have to click the OK button (usually occurred every other minute).

Visual Basic Editor Compile Error Dialog

Being new to using the Visual Basic Editor, I thought this was just normal and I had to live with the annoying pop-ups.  After I got more comfortable with the editor I started playing around with the options and stumbled upon a setting that I am so thankful exists!  This setting allowed me to turn off the annoying syntax error message alerts and I have not seen one since!

Steps To Get Rid Of The Syntax Error Alerts

Step 1: In the Visual Basic Editor (shortcut: Alt + F11) open the Tools menu and select Options…

Remove VBE Error Alerts in Microsoft Excel Writing Macros

Step 2: In the Options dialog box, ensure the Auto Syntax Check checkbox is NOT checked in the Code Settings section.  This turns off the error messages while still coloring incorrect syntax code with red font.

Remove VBA Error Alerts Auto Syntax Check Excel VBA Macros

Hit the OK button and you should be error message free from now on! Woohoo!!

My Question To You!

So I’m curious, was I just naive or did it take you a long time to figure out how to rid your life of VBA Error Alerts? Leave a comment below and let me know how long it took you!


Hidden Hacks For VBA Macro Coding

After 10+ years of creating macros and developing add-ins, I’ve compiled all the hacks I wish I had known years ago!

Hidden Hacks For VBA Macro Coding

Keep Learning

Chris Newman

Chris Newman

Chris is a finance professional and Excel MVP recognized by Microsoft since 2016. With his expertise, he founded TheSpreadsheetGuru blog to help fellow Excel users, where he shares his vast creative solutions & expertise. In addition, he has developed over 7 widely-used Excel Add-ins that have been embraced by individuals and companies worldwide.

 

maseur

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

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

Доброй ночи, форумчане. Такая вот проблемма.
По ходу выполнения макроса, он должен выделить непустые строки с последней до первой.  По этому коду:

Rows(«1:1»).Delete
        LastRow = Cells.Find(What:=»*», SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
   Range(Cells(1, 1), Cells(LastRow, «bd»)).Select

В том случае, если нет ни одной такой строки (пустой лист) появляется сообщение об ошибке (rine time errore 91).
Как подправить код, чтобы такая ситуация не останавливала макрос. Чтобы «ошибка» игнорировалась и он продолжал выполняться.

 

EducatedFool

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

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

#2

21.01.2013 03:30:45

Первой строкой в макросе:

Код
On Error Resume Next

PS: Эта директива — наиболее часто встречающаяся строка в моих программах.
Она у меня даже добавляется в начало макроса автоматически, при создании новой процедуры или функции.

Изменено: EducatedFool21.01.2013 03:31:23

 

Johny

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

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

#3

21.01.2013 08:38:12

Если Вы знаете предполагаемое место, где может быть ошибка, то после этого места необходимо вставить вот эту строку:

Код
On Error GoTo 0

Если не поставить эту строчку, то макрос будет работать в режиме «Ошибка», и если далее в коде опять возникнет ошибка, то VBA не будет на неё реагировать. Другими словами, «On Error GoTo 0» возвращает VBA в нормальный режим.

There is no knowledge that is not power

 

maseur

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

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

Спасибо за советы.
Выбрал код от EducatedFool, поскольку им проще пользоваться.
Спасибо большое.

 

Johny

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

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

#5

23.01.2013 09:24:50

Цитата
maseur пишет:
Выбрал код от EducatedFool,

Код от EducatedFool — единственный в данной теме, поэтому непонятно, из чего Вы выбирали.

Цитата
maseur пишет:
поскольку им проще пользоваться.

А это тут причём? Я лишь предупредил о подводных камнях.

There is no knowledge that is not power

 

iba2004

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

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

#6

23.01.2013 09:29:30

off: Кому проще??? Excel’ю??? :о))

Хитрости »

2 Декабрь 2011              57152 просмотров


Как запретить сообщения?

Статья может показаться странной, но…Спрос на данную тему достаточно велик. Тем, кто программирует на VBA приходится делать разнообразные вещи, для выполнения которых используются вызовы стандартных Excel-вских команд и методов. Команды в свою очередь могут выдавать сообщения, которые совершенно не нужны при выполнении кода. Яркий пример — удаление листа из книги. При попытке удаления листа появляется запрос:

Такое предупреждение не может быть лишним с точки зрения ручного удаления листа — вдруг кнопка Удалить была нажата по ошибке. Но при выполнении кода подобные сообщения «стопорят» код и могут стать очень ощутимой помехой автоматизации процессов. К примеру ниже приведен код удаления листа:

Sub Del_Sheet()
    ActiveSheet.Delete
    MsgBox "Лист удален(или нет, смотря что Вы нажали)", vbInformation, "www.excel-vba.ru"
End Sub

Запустите его и увидите, что приходится нажимать «Да» в стандартном окне Excel, чтобы код продолжился и показал уже наше сообщение. Т.е. сначала пользователь увидит стандартное окно предупреждения Excel и пока не сделает выбор код дальше не пойдет и не покажет наше сообщение. Не совсем удобно, особенно когда надо обойти штук 10 таких сообщений(часто это бывает при работе в циклах). К тому же, если пользователь откажется от удаления — лист так и не будет удален. А это уже может быть очень критично для выполнения кода в дальнейшем.
Проблема устраняется очень просто:

Sub Del_Sheet()
    Application.DisplayAlerts = False
    ActiveSheet.Delete
    MsgBox "Лист удален", vbInformation, "www.excel-vba.ru"
    Application.DisplayAlerts = True
End Sub

Команда Application.DisplayAlerts = False «подавляет» показ системных сообщений. Это касается практически всех сообщений Excel, даже тех, что появляются перед закрытием книги без сохранения. К чему я это специально уточняю? К тому, что следует помнить, что необходимо всегда возвращать значение данного свойства в True. Иначе может получиться так, что код Вы выполнили, никаких лишних сообщений не получили. Но значение не вернули. И тогда Вы рискуете вследствие случайного нажатия того же удаления листа, вместо привычного предупреждения просто лишиться листа со всеми данными. А попытавшись закрыть книгу без сохранения, чтобы заново открыть и вернуть лист — не увидеть стандартного вопроса: «Сохранить изменения в книге?» — книга будет закрыта и возможно даже сохранена автоматически.
Поэтому отключение показа сообщений сводится к простому алгоритму:

'отключаем показ сообщений
Application.DisplayAlerts = False
'производим действия, в результате которых может появится назойливое и ненужное сообщение
'какой-то код
'обязательно возвращаем показ сообщений
Application.DisplayAlerts = True

Но следует так же учитывать, что некоторые сообщения невозможно отменить даже этим методом. Например, при открытии кодом книги с нарушенными связями Excel запросит их обновление и указание источника, если это задано в свойствах книги. Чтобы избежать сообщений об изменении связей при открытии книг кодом можно использовать свойство книги UpdateLinks:

Workbooks.Open FileName:="C:Documentsкнига1.xlsx", UpdateLinks:=False

Поэтому если вдруг Вам посчастливилось нарваться на сообщение, которое не отменяется командой Application.DisplayAlerts = False, то имеет смысл присмотреться к методам и свойствам объекта(или параметрам метода), который это сообщение провоцирует.


Статья помогла? Поделись ссылкой с друзьями!

  Плейлист   Видеоуроки


Поиск по меткам

Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика

Существует три типа ошибок в программировании: (a) синтаксические ошибки, (b) ошибки времени выполнения и (c) логические ошибки.

Синтаксические ошибки

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

Function ErrorHanlding_Demo()
   dim x,y
   x = "Tutorialspoint"
   y = Ucase(x
End Function

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

Ошибки времени выполнения, также называемые исключениями, возникают во время выполнения после интерпретации.

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

Function ErrorHanlding_Demo1()
   Dim x,y
   x = 10
   y = 20
   z = fnadd(x,y)
   a = fnmultiply(x,y)
End Function

Function fnadd(x,y)
   fnadd = x + y
End Function

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

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

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

Например, деление числа на ноль или написанного скрипта, который входит в бесконечный цикл.

Err Object

Предположим, если у нас есть ошибка во время выполнения, то выполнение останавливается, отображая сообщение об ошибке. Как разработчик, если мы хотим зафиксировать ошибку, то используется Error Object.

пример

В следующем примере Err.Number дает номер ошибки, а Err.Description – описание ошибки.

Err.Raise 6   ' Raise an overflow error.
MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description
Err.Clear   ' Clear the error.

Обработка ошибок

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

On Error { GoTo [ line | 0 | -1 ] | Resume Next }

Линия GoTo

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

Перейти 0

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

GoTo -1

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

Продолжить дальше

Указывает, что при возникновении ошибки во время выполнения элемент управления переходит к оператору, который следует сразу за оператором, в котором произошла ошибка, и выполнение продолжается с этой точки.

Возможно, вам также будет интересно:

  • Vba если ошибка тогда
  • Vba если ошибка то дальше
  • Vba если ошибка msgbox
  • Vba word ошибка 5941
  • Vba excel пропуск ошибок

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии