Vba excel отключить все сообщения

DisplayAlerts = False не всегда помогает.
Следует учитывать, что некоторые сообщения невозможно отменить даже этим методом. Например, при открытии кодом книги с нарушенными связями Excel запросит их обновление и указание источника, если это задано в свойствах книги. Чтобы избежать сообщений об изменении связей при открытии книг кодом можно использовать свойство книги UpdateLinks:
Workbooks.Open FileName:=»C:Documentsкнига1.xlsx», UpdateLinks:=False

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

Источник тут: https://www.excel-vba.ru/chto-… bshheniya/

Хитрости »

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


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

Статья может показаться странной, но…Спрос на данную тему достаточно велик. Тем, кто программирует на 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
ссылки
статистика

I have some code in VB that saves all XLSM files as XLSX. I already have the code that will do that for me, but dialog boxes show up for every action. This was fine for a few dozen files. However, I’m going to use this on hundreds of XLSM files at once, and I can’t just sit at my computer all day clicking dialog boxes over and over.

The code I’ve tried is pretty much:

Application.DisplayAlerts = False

While this doesn’t cause an error, it also doesn’t work.

The boxes give a warning about enabling macros, and also warn that saving as XLSX strips the file of all macros. Considering the type of warnings, I suspect that they’ve restricted turning off those dialog boxes due to the security risk.

Since I’m running this code in Excel’s VB editor, is there perhaps an option that will allow me to disable dialog boxes for debugging?

I’ve also tried:

Application.DisplayAlerts = False       
Application.EnableEvents = False        
' applied code
Application.DisableAlerts = True
Application.EnableEvents = True

Neither of those worked.

Edit:

Here’s what the code above looks like in my current code:

Public Sub example()
Application.DisplayAlerts = False
Application.EnableEvents = False

For Each element In sArray
    XLSMToXLSX(element)
Next element

Application.DisplayAlerts = False
Application.EnableEvents = False
End Sub

Sub XLSMToXLSX(ByVal file As String)
    Do While WorkFile <> ""
        If Right(WorkFile, 4) <> "xlsx" Then
            Workbooks.Open Filename:=myPath & WorkFile

            Application.DisplayAlerts = False
            Application.EnableEvents = False

            ActiveWorkbook.SaveAs Filename:= _
            modifiedFileName, FileFormat:= _
            xlOpenXMLWorkbook, CreateBackup:=False

            Application.DisplayAlerts = True
            Application.EnableEvents = True

            ActiveWorkbook.Close
        End If
        WorkFile = Dir()
    Loop
End Sub

I also surrounded the For loop, as opposed to the ActiveWorkbook.SaveAs line:

Public Sub example()
For Each element In sArray
    XLSMToXLSX(element)
Next element
End Sub

Finally, I shifted the Application.DisplayAlerts above the Workbooks.Open line:

Sub XLSMToXLSX(ByVal file As String)
    Do While WorkFile <> ""
        If Right(WorkFile, 4) <> "xlsx" Then
            Workbooks.Open Filename:=myPath & WorkFile

            Application.DisplayAlerts = False
            Application.EnableEvents = False

            ActiveWorkbook.SaveAs Filename:= _
            modifiedFileName, FileFormat:= _
            xlOpenXMLWorkbook, CreateBackup:=False

            Application.DisplayAlerts = True
            Application.EnableEvents = True

            ActiveWorkbook.Close
        End If
        WorkFile = Dir()
    Loop
End Sub

None of those work as well.

Edit:

I’m using Excel for Mac 2011, if that helps.

How to stop an Excel alert window or message box from appearing while running a macro. This is particularly useful when running a macro that needs to close a workbook and you don’t want the «Save» dialogue box to appear.

Sections:

Code

Example Close Workbook

Notes

Code

Turn Alerts Off

Application.DisplayAlerts = False

Turn Alerts On

Application.DisplayAlerts = True

f3852f16f10331c09120cadd0def390b.jpg

Example Close Workbook

The number one reason to use this is to allow Excel to open a workbook, get data from it, and close it without saving changes or seeing a pop-up message box asking to save the file.

Here is an example that will close the workbook:

Sub test_save()

Application.DisplayAlerts = False


'Code to run here
ActiveWorkbook.Close


Application.DisplayAlerts = True

End Sub

6113db589eb7b08eeb8b4166d5473c68.jpg

When I run the above macro, the workbook will close without any notices, messages, or warnings.

However, if I comment-out the lines with DisplayAlerts and run it, the process is different.

Here is the commented-out code:

65eece8befe523a556ff58bb71f64bc9.jpg

Here is what happens when I run it:

74d379658d27bacce1db0fa2e4b78265.jpg

That window appears and the user has to click a button to proceed. This is not a very user-friendly setup, especially if a novice user is trying to use a macro that you created and they don’t know what is going on.

Notes

This is a very helpful piece of code to include in your macros. Keep this information in the back of your mind so you can use it when needed.

In the sample file for this tutorial I commented-out every line of code so you can uncomment what you want to test it.

Make sure to download the sample Excel file for this tutorial to work with these examples.

Similar Content on TeachExcel

Run a Macro When a Specific Cell Changes in Excel

Tutorial:
Run a macro in Excel when a specific cell is changed; this also covers when a cell within…

Create a Column Chart with a Macro in Excel

Macro: This macro adds a column chart to Excel. This is an easy to use macro that allows you to q…

Create a Bar Chart With a Macro in Excel

Macro: Create a bar chart in Excel with this macro. You will be able to quickly and easily turn a…

Run a Macro when a User Does Something in the Workbook in Excel

Tutorial:
How to run a macro when a user does something within the Workbook in Excel, such as openi…

Stop Excel Events from Triggering when Running a Macro

Tutorial: Create a macro that will run without triggering events, such as the Change event, or Activ…

Subscribe for Weekly Tutorials

BONUS: subscribe now to download our Top Tutorials Ebook!

Imagine you’ve written a VBA code that writes in a file, saves and closes it. Now, every time you run your code it shows a popup message in Excel like this (if the file already exists).

etg

You can click OK for one time but if your code does the same for 100s of the time then it is not feasible to do so. You don’t want this to happen. You need to automate this process. To do so, just add these lines to your code.

Sub DisablUpdates()
With Application.DisplayAlerts = False                ‘Turns of alerts.AlertBeforeOverwriting = False       ‘Turns of overwrite alerts.ScreenUpdating = False               ‘Turns of screen updatingEnd With
*****************‘Your Code here‘*****************
With Application.DisplayAlerts = True                 ‘Turns back on alerts

.AlertBeforeOverwriting = True        ‘Turns on Overwrite alerts

.ScreenUpdating = True                ‘Turns on screen updating

End With
End Sub

Code Explanation 

This code not only disables VBA alerts but also increases the time efficiency of the code. Let’s see how.

To use this code, you first need to enable VBA to excel of course.

At the beginning of the code, we disabled all unnecessary operations and in the end, we turned them on so that your system works as it was working before.

With Application: This line gives us access to all properties of the Application object. We can invoke them just by using ‘.’ (dot) operator if called using “With” Block.

.DisplayAlerts = False: This is a property of the application object. See here we have called it using “.” operator just.This line disables all alerts of the closing file, overwriting, or opening an already open file.

.AlertBeforeOverwriting = False: This line disables alert overwriting cells during drag down operation or any other on sheet alert.

.ScreenUpdating = False: in almost every code you move from one cell to another, one sheet to another and one workbook to another. If you don’t add this line, you will see screen flickering. Every movement you do on the system using VBA will be displayed. This causes time overhead and can cause your system to hang. To save time and resources always incorporate this line.

The bottom block must also be executed to turn your excel back to normal and to see results. You are doing nothing but turning every switch on you turned off in the Write this block before each End Sub and Exit Sub.

With Application

.DisplayAlerts = True

.AlertBeforeOverwriting = True

.ScreenUpdating = True

End With

This is one of the most common questions of Excel VBA Programmer Interviews. There is a 90% chance that you will be asked this question in Advanced Excel and VBA questions.

I hope you got your solution. If not, do use the comments section to ask a more personalised question.

Download file

Related Articles:

How to Change The Default Printer Using VBA in Microsoft Excel 2016
How to Display A Message On The Excel VBA Status Bar
How to Insert Pictures Using VBA In Microsoft Excel 2016
How to Add And Save New Workbook Using VBA In Microsoft Excel 2016
How to use the Conditional Formatting using VBA in Microsoft Excel

Popular Articles:

50 Excel Shortcuts to Increase Your Productivity

How to use the VLOOKUP Function in Excel

How to use the COUNTIF function in Excel

How to use the SUMIF Function in Excel

Понравилась статья? Поделить с друзьями:
  • Vba excel отбросить дробную часть
  • Vba excel остановить таймер
  • Vba excel остановить процедуру
  • Vba excel остановить выполнение цикла
  • Vba excel остановить выполнение программы