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

Access для Microsoft 365 Access 2021 Access 2019 Access 2016 Access 2013 Access 2010 Access 2007 Еще…Меньше

Макрокоманда УстановитьСообщения предназначена для включения и отключения системных сообщений в классической базе данных Access.

Примечание: Эта макрокоманда доступна только для доверенных баз данных.

Настройка

Макрокоманда УстановитьСообщения имеет следующий аргумент:

Аргумент макрокоманды

Описание

Включить сообщения

Указывает, будут ли выводиться системные сообщения. Выберите значение Да (чтобы включить системные сообщения) или Нет (чтобы отключить системные сообщения) в поле Включить сообщения в разделе Аргументы макрокоманды окна конструктора макросов. По умолчанию используется значение Нет.

Примечания

Это действие позволяет предотвратить прекращение модальный и полей сообщений макрос. Однако сообщения об ошибках отображаются всегда. Кроме того, Access выводит все диалоговые окна, в которые требуется ввести данные, кроме нажатия кнопки (например, «ОК», «Отмена», «Да»или «Нет»), например любое диалоговое окно, в которое требуется ввести текст или выбрать один из нескольких параметров.

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

После завершения работы макроса Access автоматически включает вывод системных сообщений.

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

Хотя макрокоманда УстановитьСообщения упрощает работу с макросом, следует соблюдать осторожность при отключении системных сообщений. При появлении некоторых предупреждающих сообщений нужно прервать выполнение макроса. Не следует использовать эту макрокоманду, пока не проверен результат выполнения всех команд в макросе.

Чтобы запустить макрокоманду УстановитьСообщения в модуле Visual Basic для приложений (VBA), используйте метод SetWarnings объекта DoCmd.

Нужна дополнительная помощь?

Нужны дополнительные параметры?

Изучите преимущества подписки, просмотрите учебные курсы, узнайте, как защитить свое устройство и т. д.

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

2.4. Использование DoCmd.RunSQL.
Иногда советуют поставить DoCmd.SetWarnings False передDoCmd.RunSQL, но это крайне опасно. Это требует добавить DoCmd.SetWarnings True где только можно, особенно в обработчиках ошибок. В противном случае Аксесс в какой-нибудь момент вообще перестанет выдавать предупреждения на удаление и т.п. (в том числе и предупреждения об ошибках) до конца работы программы. Также есть возможность, что в отладочный период Вы остановите выполнение кода ДО включения сообщений, что тоже повлечёт за собой выше описанный результат. Но если Вы решили использовать данную конструкцию, то используйте её следующим образом.

On Error Goto mis …
DoCmd.SetWarnings False
DoCmd.RunSQL …
DoCmd.SetWarnings True …
Exit Sub mis:
DoCmd.SetWarnings True

2.5. Противопоказания к использованию конструкции Application.SetOption
Подтверждения исчезнут во всей аппликации насквозь, в том числе там, где это не планировалось. Это можно делать только в том случае, если соблюдены два условия:
Пользователь лишен права на удаление тех объектов, которые нужны для нормальной работы программы, и его устраивает отсутствие подтверждений при удалении/редактировании данных через экран.
Подтверждения не отключаются, если в приложении работает сам разработчик.

2.6. Возможность отката
Нередко возникает необходимость при возникновении ошибок отменить результат исполнения целого ряда запросов. DoCmd.RunSQL такой возможности не дает. CurrentDb.Execute, в отличие от него, позволяет откатить транзакцию, в которую включено то, что посчитает нужным программист. В CurrentDb.Execute есть опция dbFailOnError — она относится только к выполнению конкретного запроса, т.е. отвечает только за то, будет ли запрос при ошибке откачен целиком и будет возвращена ошибка, или же возможно частичное выполнение запроса.
Пример отката внешней транзакции:
Public Function Test() On Error Goto Rollback_Label DBEngine(0).BeginTrans CurrentDb.Execute «Запрос1», dbFailOnError CurrentDb.Execute «Запрос2», dbFailOnError CurrentDb.Execute «Запрос3», dbFailOnError DBEngine(0).CommitTrans Exit_Label: Exit Function Rollback_Label: DBEngine(0).Rollback Resume Exit_Label End Function

В данном случае если не выполнится хотя бы один запрос, то все запросы «откатятся».

Annoyed with Access prompt pop-ups encountered meanwhile performing action query? Want to suppress Microsoft Access action query warning messages but don’t know how?

Well to perform MS Access Action Query Warning Messages on/off you need to use ‘setwarning’ option. Microsoft Access setwarnings are mainly used to turn system messages on/off in the Access database. these Access setwarnings can be used in various ways and in different circumstances.

To know how to add setwarnings in Access 2010/2013/2016/2019 macro. OR how to perform Microsoft Access setwarnings on/off. You need to just go through this post.

So, let’s dive into it…..!

Rated Excellent on Trustpilot
Free MS Access Database Repair Tool
Repair corrupt MDB and ACCDB database files and recover deleted database tables, queries, indexes and records easily. Try Now!

Download
By clicking the button above and installing Stellar Repair for Access (14.8 MB), I acknowledge that I have read and agree to the End User License Agreement and Privacy Policy of this site.

About MS Access Setwarnings:

By default, MS Access takes your confirmation each time before deleting up any object from the navigation pane or while running an action query. If this pop-up message annoys you to work flawlessly in your database then you can turn it OFF. Whenever you want to allow the appearance of such a message again then turn it ON.

This task is possible with MS Access setwarnings. This option of set warnings is mainly used to suppress Microsoft Access action query warning messages.

What’s The Need Of Suppressing Microsoft Access Action Query Warning Messages?

At the time of executing action queries in MS Access you may want to prevent any kind of user intervention. Like pressing OK in the warning messages while making an update, creating a table, deleting, or appending query.

Running such kind of Access query without switching off your system messages will annoy you with the intervention of several warning messages.

Here is the example of one such warning message encountered meanwhile executing the  Make-Table query:

Make-Table query

For disabling these Access prompt pop-ups messages, you need to make simple configuration modifications in Access options.

How To Suppress Microsoft Access Action Query Warning Messages?

Suppress Microsoft Access Action Query Warning Messages

Method 1:  Microsoft Access VBA docmd.setwarnings

The DoCmd.SetWarnings method is used to perform SetWarnings action in VB(Visual Basic).

Syntax:

expression.SetWarnings (WarningsOn)

expression A variable that represents a DoCmd object.

Parameters

Name Required/Optional Data type Description
WarningsOn Required Variant Use True (1) to turn on the display of system messages and False (0) for turning it off.

Remarks:

Make use of the Microsoft Access VBA docmd.setwarnings for turning system messages OFF/ON.

If you turn OFF the visibility option of system messages in Visual Basic, you must turn it back on. Otherwise, it will remain OFF even if you try pressing Ctrl+Break. Or Visual Basic meets any breakpoint.

For disabling the visibility of MS Access action query warning messages, you need to set the options to OFF in the command.

Here is the example to show how to turn off Access warning messages:

Private Sub cmdRunMakeTable_Click()

DoCmd.Hourglass True

Turns off the Access warning messages

DoCmd.SetWarnings False

DoCmd.OpenQuery “mktqry_MakeNewTable”

DoCmd.Hourglass False

Turns the Access warning messages back on

DoCmd.SetWarnings True

End Sub

Do such a setting only if you are completely sure that your actions will not make any problems. Or unless you are completely sure about the outcomes of the actions. Otherwise don’t do it.

Method 2: SetWarnings Macro Action

SetWarnings macro action is used to turn system messages on/off in Access database application. You can also use this action to stop the message box and modal warnings which prevent the execution of the macro.

Note: if the database is not trusted one then avoid performing this action.

Setting

The MS Access SetWarnings macro action includes the following argument.

Action argument Description
Warnings On Specifies whether system messages are displayed. Click Yes (to turn on system messages) or No (to turn off system messages) in the Warnings On box in the Action Arguments section of the macro design window. The default is No.

How To Use:

Access shows pop-up dialog boxes that require input like a dialog box which asks you to enter any text or choose one out of several options.

Perform this SetWarnings Macro action with Warnings On argument set to No. This will show the same effect as tapping to the ENTER option whenever any warning message box appears.

Usually, OK or Yes option is chosen in the warning or message box.

After the macro finishes the execution task, Access will automatically turn on the visibility of the system messages.

You can also use this SetWarnings Macro action with the Echo macro action. This will hide the appearance of macro results unless its execution completely gets over.

SetWarnings macro action makes this simple to interact with macros. but you have to care about turning off system messages.

 Unless and until you are so sure about the outcome of any macro actions, avoid using it.

Steps To Use A Macro To Turn The Messages Off/On

From the drop-down list of macro, the builder chooses the SetWarnings action.

If you are unable to see SetWarnings action listed, under the Design tab, in the group of Show/Hide. make a check whether the Show All Actions is also selected.

  1. Within the SetWarnings action, tap to the arrow present next to Warnings On. After then select the No
  2. Put the required macro actions for performing tasks that you want to perform with confirmation messages turned off.
  3. Now choose the SetWarnings After then tap to the arrow present next to the Warnings On and choose the Yes option.
  4. Close the Macro Builder and save the macro. In the end, save the form.

Method 3: Using the RunSQL

There are several ways to run an Access action query using code or macros. In this method, we will learn to execute an action query in preference to RunSQL.

Using OpenQuery is similar like, double-tapping the action query on the query tab present in the Database window. This also works the same but it is a little less clear what Access macro is actually doing.

While running an action query, the application pops up two dialog box messages:

A nuisance dialog:

ActionQuery1

Important details of results and errors:

ActionQuery2

The SetWarnings action of macro will suppress these dialogues messages. It suppresses both messages. So, you won’t get any idea whether the action gets completed as you have expected OR not.

Execute method gives a much more effective solution if you don’t have any issue of using code instead of the macro.

In the Access module, run the action query like this:
DBEngine (0)(0).Execute “Query1”, dbFailOnError

If the query executes without any dialogue message, so you don’t need to use SetWarnings. To hide the appearance of the result, type the following line after the above coding line:

MsgBox DBEngine(0)(0).RecordsAffected & ” record(s) affected.”

If you get some error, after using dbFailOnError then make use of the transaction and rollback on error.

Method 4: Turn action query confirmation messages off for a database

Turn action query confirmation messages off for a database

Make use of the SetWarnings action in an AutoExec macro for turning OFF the MS Access action query warning messages.

Important:

The action won’t execute if the database having the macro is not the trusted one. to get information about how to identify the trusted database check out the article Decide whether to trust a database.

Note:

If a macro named AutoExec is already present there then in that case open the macro in Design view, and then perform steps 2 to 4 of the below-given steps.

  1. From the Create tab, choose the Macros & Code After then tap to the Macro option.
  2. From the drop-down list of Macro Builder choose the SetWarnings
    • If you don’t get the SetWarnings action listed over here. Then go to the Design tab, present within the Show/Hide Also make to select the Show All Actions option.
  3. Within the SetWarnings action, tap to the arrow present next to Warnings On option and then choose the option which you want.
  4. Tap to the Save
  5. In the opened Save As dialog box, type AutoExec.
  6. Hit the OK option and then close the Macro Builder. Macro will run next time when you open the database.

For more information about how to create macros, see the article: 3 Quick Ways To Create Macro In MS Access 2010/2013/2016/2019 Database.

Wrap Up:

Hopefully, you have got enough idea of how to turn action query confirmation messages on or off using setwarning. So, don’t let these annoying MS Access security warnings hampering your work anymore.

Apart from this if you want to get knowledge on some other topic regarding the Access database. Then ask it freely in our comment section.

tip Still having issues? Fix them with this Access repair tool:

This software repairs & restores all ACCDB/MDB objects including tables, reports, queries, records, forms, and indexes along with modules, macros, and other stuffs effectively.

  1. Download Stellar Repair for Access rated Great on Cnet (download starts on this page).
  2. Click Browse and Search option to locate corrupt Access database.
  3. Click Repair button to repair & preview the database objects.

Pearson Willey is a website content writer and long-form content planner. Besides this, he is also an avid reader. Thus he knows very well how to write an engaging content for readers. Writing is like a growing edge for him. He loves exploring his knowledge on MS Access & sharing tech blogs.

-22 / 1 / 0

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

Сообщений: 217

1

Пропуск сообщений об ошибке

25.10.2018, 13:35. Показов 3548. Ответов 10


Студворк — интернет-сервис помощи студентам

Всем доброго времени Уважаемые форумчане, Админы и программисты!

Такой вопрос.
Как устранить окно сообщения в Access об ошибке, если не найдено значение
с ключевым полем в таблице и.п.
Чтобы вместо этого окна, запускалось, например: какое-нибудь окно.
Скрин прикрепляю!

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

Миниатюры

Пропуск сообщений об ошибке
 



0



10066 / 5143 / 1283

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

Сообщений: 14,472

25.10.2018, 20:25

2

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

Как устранить окно сообщения в Access об ошибке, если не найдено значение

Организовать проверку значения (состояния) в VBA + Обработчик ошибок на событии OnLoad (Загрузка формы).
Если ошибка связана с данными то на событии OnCurrent (Тек. Запись)

Куда уж проще.



0



-22 / 1 / 0

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

Сообщений: 217

25.10.2018, 21:52

 [ТС]

3

Eugene-LS, Ну не совсем. Дело в том, что это сообщение появляется при обновлении. т.е. когда сканируется штрих-код. И если штрих-код отсутствует в базе, то соответственно появляется это сообщение. Я только не могу ни как от него избавиться. Так сказать скрыть)))))
В VBA я еще плаваю, не совсем еще понимаю, что к чему. Может все-таки поможете?!



0



10066 / 5143 / 1283

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

Сообщений: 14,472

25.10.2018, 22:06

4

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

Дело в том, что это сообщение появляется при обновлении. т.е. когда сканируется штрих-код.

Тогда обрабатывайте AfterUpdate (После Обновления) конкретного поля формы.
Насколько помню, сканер эмулирует ввод с клавиатуры …



0



-22 / 1 / 0

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

Сообщений: 217

26.10.2018, 00:13

 [ТС]

5

Eugene-LS, Ну может покажите как выглядит сам код!?))))



0



Braser

315 / 131 / 35

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

Сообщений: 1,349

26.10.2018, 05:28

6

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

Ну может покажите как выглядит сам код!?))))

к вам такое же пожелание, вы бы процедуру обработки выложили, интересно как она выглядит…

Visual Basic
1
On Error Resume Next

не помогает?



0



315 / 131 / 35

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

Сообщений: 1,349

26.10.2018, 12:04

7

Может это чем-то поможет



0



295 / 256 / 68

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

Сообщений: 570

26.10.2018, 12:12

8

А это точно VBA? Что-то больше на ошибку в макросах похоже. Базу давайте



0



nape63

162 / 61 / 13

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

Сообщений: 176

26.10.2018, 12:18

9

Лучший ответ Сообщение было отмечено BaumEV как решение

Решение

Для начала надо найти код ошибки. А потом уже обрабатывать ее.

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Private Function PressButt(intTypeButt As Integer)
On Error GoTo Err_PressButt
 
'ЗДЕСЬ КАКОЙ-ТО КОД
 
Exit_PressButt:
    Exit Function
Err_PressButt:
   Debug.Print Err
    'If Err = ... Then
    '  Resume Exit_PressButt
   ' End If
    MsgBox Err.Description
    Resume Exit_PressButt
End Function



0



10066 / 5143 / 1283

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

Сообщений: 14,472

26.10.2018, 17:23

10

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

Чтобы вместо этого окна, запускалось, например: какое-нибудь окно.

Терминология однако! — кричит громче любых слов о подготовке вопрошающего ….
— Окно — это окно приложения целиком (объект Window)
— Внутри окна открываются формы (объект Form)

… Может вам стоит литературку какую (по тематике) для начала полистать?!
Успехов!

PS
Такое делается вставкой обработчика ошибок в процедуру …



0



162 / 61 / 13

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

Сообщений: 176

27.10.2018, 00:31

11

Eugene-LS, Вообще-то окно оно и в Африке оно. Форма это тоже окно, еще один ребенок от главного окна. Даже messagebox это тоже окно ). Ну это так, если к словам… А так, да, к сожалению часто уровень вопрошающих энтузиазма не добавляет.



0



I use a form to run a few codes on a database in Access. During update or deletion Access asks whether you want to update or delete.

I would like to know if there is any way of turning off these system messages or let the user choose his preference on whether he would like thoses messages to pop up or not.

Blackbam's user avatar

Blackbam

17.6k27 gold badges97 silver badges150 bronze badges

asked Dec 18, 2008 at 13:46

tksy's user avatar

Don’t foget to turn these back on.

DoCmd.SetWarnings false
DoCmd.SetWarnings true

Application.DisplayAlerts = false
Application.DisplayAlerts = true

answered Dec 18, 2008 at 13:48

LeppyR64's user avatar

LeppyR64LeppyR64

5,2512 gold badges31 silver badges35 bronze badges

7

Понравилась статья? Поделить с друзьями:
  • Access номер ошибки 32004
  • Acbsp exe ошибка как исправить assassins creed brotherhood
  • Academybugs com 25 ошибок
  • Acbrandres dll autocad ошибка
  • Ac4bfsp exe системная ошибка msvcr100 dll