Excel vba no messages

Содержание

  1. Excel VBA Crashing, No error messages, no idea!
  2. Функция MsgBox
  3. Синтаксис
  4. Параметры
  5. Возвращаемые значения
  6. Примечания
  7. Пример
  8. См. также
  9. Поддержка и обратная связь
  10. VBA Excel. Функция MsgBox (синтаксис, параметры, значения)
  11. Синтаксис функции
  12. Параметры функции
  13. Константы параметра «Buttons»
  14. Тип и количество кнопок
  15. Стиль значка

Excel VBA Crashing, No error messages, no idea!

Help! I’ve been building a large macro for 2+ months on a PC with Windows 7 and Excel 2010. I have the calculation procedures split over multiple smaller macros that perform the actual calculations.

Everything was working fine until I came in after the weekend. Now, when I try to run the macro through hitting the Play button in VBA, Excel/VBA locks up with no error message. Similarly, when I open the workbook and go to the Developer Tab>Macros, the file crashes when I just simply click on the name of the master macro. Same deal with a button on a worksheet that I have assigned to the master macro. All of this worked before the weekend, and I have NO idea what could have changed.

I’ve tested a few of the subroutines, and the simple ones that clear individual worksheets to zero-out the calculations work just fine with no lock-ups. But, anytime that I try to run the master macro, or the subroutines that pull information from worksheets (esentially, anything involving my public variables), the whole thing crashes. This same error happens when I go to Debug>Compile in VBA. It’s terribly frustrating since there is NO error message, no run-time error, nothing to show me what goes wrong.

I found some previous posts that recommended changing code like this:

to something more specific like:

So, I changed all of my sheet references to call the activeworkbook first, but that still didn’t help.

My guess is that it’s a security issue, but I am not familiar enough with MS Office to know. any ideas?

Источник

Функция MsgBox

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

Хотите создавать решения, которые расширяют возможности Office на разнообразных платформах? Ознакомьтесь с новой моделью надстроек Office. Надстройки Office занимают меньше места по сравнению с надстройками и решениями VSTO, и вы можете создавать их, используя практически любую технологию веб-программирования, например HTML5, JavaScript, CSS3 и XML.

Синтаксис

MsgBox (сообщение, [ кнопки, ] [ заголовок, ] [ файл_справки, контекст ])

Синтаксис функции MsgBox включает следующие именованные аргументы:

Часть Описание
сообщение Обязательный аргумент. Строковое выражение, отображающееся в диалоговом окне. Максимальная длина строки аргумента сообщение составляет приблизительно 1024 знака и зависит от их ширины. Если запрос состоит из нескольких строк, можно разделить строки с помощью символа возврата каретки (Chr(13)), символа канала строк (Chr(10)) или символа возврата каретки — сочетания символов канала строки (Chr(13) &Chr(10)) между каждой строкой.
кнопки Необязательный аргумент. Числовое выражение, являющееся комбинацией значений, указывающих количество и тип отображаемых кнопок, стиля значков, выбранной по умолчанию кнопки и модальности окна сообщения. Если аргумент кнопки пропущен, по умолчанию используется значение 0.
заголовок Необязательный аргумент. Строковое выражение, отображаемое в заголовке диалогового окна. Если аргумент заголовок пропущен, в заголовке выводится имя приложения.
файл_справки Необязательный аргумент. Строковое выражение, определяющее файл, в котором содержится контекстная справка для данного диалогового окна. Если задан аргумент файл_справки, необходимо также указать аргумент контекст.
контекст Необязательный аргумент. Числовое выражение, представляющее собой номер контекста, присвоенный автором справки соответствующему разделу. Если задан аргумент контекст, необходимо также указать аргумент файл_справки.

Параметры

Константа Значение Описание
vbOKOnly 0 Отображается только кнопка ОК.
vbOKCancel 1 Отображаются кнопки ОК и Отмена.
vbAbortRetryIgnore 2 Отображаются кнопки Прервать, Повторить и Пропустить.
vbYesNoCancel 3 Отображаются кнопки Да, Нет и Отмена.
vbYesNo 4 Отображаются кнопки Да и Нет.
vbRetryCancel 5 Отображаются кнопки Повторить и Отмена.
vbCritical 16 Отображается значок важного сообщения.
vbQuestion 32 Отображение значка Warning Query (Запрос с предупреждением).
vbExclamation 48 Отображение значка Warning Message (Сообщение с предупреждением).
vbInformation 64 Отображается значок информационного сообщения.
vbDefaultButton1 0 По умолчанию активна первая кнопка.
vbDefaultButton2 256 По умолчанию активна вторая кнопка.
vbDefaultButton3 512 По умолчанию активна третья кнопка.
vbDefaultButton4 768 По умолчанию активна четвертая кнопка.
vbApplicationModal 0 Модальность на уровне приложения. Пользователь должен ответить на сообщение, чтобы продолжить работу в текущем приложении.
vbSystemModal 4096 Модальность на уровне системы. При ожидании ответа пользователя на сообщение приостанавливается работа всех приложений.
vbMsgBoxHelpButton 16384 Добавляет кнопку Справка в окно сообщения.
vbMsgBoxSetForeground 65536 Расположение окна сообщения на переднем плане.
vbMsgBoxRight 524288 Текст выравнивается по правому краю.
vbMsgBoxRtlReading 1048576 Система чтения справа налево для иврита и арабского языка.

Первая группа значений (0–5) отражает число и тип кнопок в диалоговом окне. Вторая группа (16, 32, 48, 64) описывает стиль значка сообщения. Третья группа (0, 256, 512) определяет активную по умолчанию кнопку. Наконец, четвертая группа (0, 4096) устанавливает модальность сообщения. При объединении чисел в итоговое значение аргумента buttons следует использовать только один аргумент из каждой группы.

Приведенные здесь константы определены в Visual Basic для приложений, что позволяет заменять ими числовые значения в любом месте программы.

Возвращаемые значения

Константа Значение Описание
vbOK 1 OK
vbCancel 2 Отмена
vbAbort 3 Прервать
vbRetry 4 Повторить
vbIgnore 5 Пропустить
vbYes 6 Да
vbNo 7 Нет

Примечания

Если одновременно указаны аргументы файл_справки и контекст, пользователь может нажать клавишу F1 (Windows) или HELP (Macintosh) для просмотра раздела справки, соответствующего аргументу контекст. Некоторые ведущие приложения, например Microsoft Excel, автоматически добавляют кнопку Справка в диалоговое окно.

Если в диалоговом окне есть кнопка Отмена, ее нажатие равносильно нажатию клавиши ESC. Если в диалоговом окне есть кнопка Справка, для него доступна контекстная справка. Однако до нажатия какой-либо другой кнопки никакое значение не возвращается.

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

Пример

В приведенном ниже примере функция MsgBox используется для вывода сообщения о критической ошибке в диалоговом окне с кнопками Да и Нет. Кнопка Нет выбрана по умолчанию. Значение, возвращаемое функцией MsgBox, зависит от нажатой пользователем кнопки. Предполагается, что DEMO.HLP является файлом справки и содержит раздел под номером контекста 1000 .

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

VBA Excel. Функция MsgBox (синтаксис, параметры, значения)

Использование функции MsgBox в VBA Excel, ее синтаксис и параметры. Значения, возвращаемые функцией MsgBox. Примеры использования.

Функция MsgBox предназначена в VBA Excel для вывода сообщения в диалоговом окне, ожидания нажатия кнопки и возврата значения типа Integer, указывающего на то, какая кнопка была нажата. Для упрощения восприятия информации, в этой статье не рассматриваются параметры, связанные с контекстной справкой и модальностью диалогового окна MsgBox.

Синтаксис функции

MsgBox ( Prompt [, Buttons ] [, Title ])

Обязательным параметром функции MsgBox является Prompt, если Buttons и Title явно не указаны, используются их значения по умолчанию. Кроме того, если необязательные параметры не указаны и возвращаемое значение не присваивается переменной, сообщение не заключается в скобки:

Пример 1

Параметры функции

Параметр Описание Значение
по умолчанию
Prompt* Обязательный параметр. Выражение типа String, отображаемое в диалоговом окне в виде сообщения. Разделить на строки можно с помощью константы vbNewLine. Нет
Buttons Необязательный параметр. Числовое выражение, которое представляет собой сумму значений, задающих номер и тип отображаемых кнопок, стиль используемого значка, тип кнопки по умолчанию. 0
Title Необязательный параметр. Выражение типа String, отображаемое в заголовке диалогового окна. Имя приложения**

*Максимальная длина параметра Prompt составляет примерно 1024 знака и зависит от их ширины.

**В Excel по умолчанию в заголовке MsgBox выводится надпись «Microsoft Excel».

Константы параметра «Buttons»

Тип и количество кнопок

Константа Описание Значение
vbOKOnly Отображается только кнопка OK. 0
vbOKCancel Отображаются кнопки OK и Cancel (Отмена). 1
vbAbortRetryIgnore Отображаются кнопки Abort (Прервать), Retry (Повторить) и Ignore (Пропустить). 2
vbYesNoCancel Отображаются кнопки Yes (Да), No (Нет) и Cancel (Отмена). 3
vbYesNo Отображаются кнопки Yes (Да) и No (Нет). 4
vbRetryCancel Отображаются кнопки Retry (Повторить) и Cancel (Отмена). 5

Стиль значка

Константа Описание Значение
vbCritical Отображается значок Critical — Критичное сообщение, сообщение об ошибке. 16
vbQuestion Отображается значок Question — Сообщение с вопросом. 32
vbExclamation Отображается значок Exclamation — Предупреждающее сообщение. 48
vbInformation Отображается значок Information — Информационное сообщение. 64

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

Источник

In this Article

  • VBA MsgBox Function
  • VBA YesNo Message Box
  • VBA Message Box Options
  • Syntax of MsgBox Function
  • Customize Message Box Title and Prompt
    • MessageBox LineBreaks
  • MsgBox Icons
    • MsgBox Icons – Information
    • MsgBox Icons – Critical
    • MsgBox Icons – Question
    • MsgBox Icons – Exclamation
  • MsgBox Variables
    • OK Message Box – vbOKOnly
    • OK Cancel Message Box – vbOKCancel
    • Yes No Message Box – vbYesNo
    • Yes No Cancel Message Box – vbYesNoCancel
    • Abort Retry Ignore Message Box – vbAbortRetryIgnore
    • Retry Cancel Message Box – vbRetryCancel
  • VBA MessageBox Examples
    • Message Box Confirmation Before Running Macro
    • Yes / No Message Box – Exit Sub
  • VBA Message Box in Access VBA

This tutorial will cover how to use the VBA MsgBox Function to display messageboxes to users (including the YesNo Messagebox). You might also be interested in our article on InputBoxes.

VBA MsgBox Function

In VBA, it’s easy to display a simple MsgBox:

MsgBox "This is a Message Box"

vba messagebox

However you can do a lot more than display a simple OK message box. Let’s quickly look at complicated example before we dive into specifics…

VBA YesNo Message Box

Below we will create a message box with:

  • A title “Message Box Title” and prompt “Text”
  • A question mark icon
  • Yes / No options instead of a simple “OK”
  • Default button = ‘No’
Dim answer As Integer

answer = MsgBox("Text", vbQuestion + vbYesNo + vbDefaultButton2, "Message Box Title")

vba yesno messagebox

The messagebox will return vbYes or vbNo depending on the user’s choice. You can then then perform different actions based on the choice:

If answer = vbYes Then
  MsgBox "Yes"
Else
  MsgBox "No"
End If

In the next section we will show you all of the options available to you when creating message boxes. Then we will introduce you to the syntax of the MsgBox Function and finally go over other message box examples.

VBA Message Box Options

Take a look at the image below. Here you will see (almost) all of the options available to you when creating message boxes. Take notice of the icons and the different buttons.

vba write messagebox code

This is a screenshot of the “MessageBox Builder” from our Premium VBA Add-in: AutoMacro. The MessageBox Builder allows you to quickly design your desired messagebox and insert the code into your code module. It also contains many other code builders, an extensive VBA code library, and an assortment of coding tools. It’s a must-have for any VBA developer.

Syntax of MsgBox Function

MsgBox( prompt [, buttons ] [, title ] [, helpfile, context ] )

prompt (Required) – This is the primary message box text.

buttons – Choose which buttons to display. If omitted, ‘OKonly’. Here you can also specify what icon to show and the default button.

title – The title at the top of the message box. If omitted, the name of the current application is displayed (ex. Microsoft Excel).

helpfile – Specify help file that can be accessed when user clicks on the ‘Help’ button. If specified, then you must also add context (below)

context – Numeric expression representing the Help context number assigned to the appropriate Help topic.

You can probably ignore the helpfile and context arguments. I’ve never seen them used.

Customize Message Box Title and Prompt

The MsgBox function allows you to customize the title and prompt messages like so:

Msgbox "Prompt",,"Title"

Another example:

Sub MsgBoxPromptTitle()
  MsgBox "Step 1 Complete. Click OK to run step 2.",, "Step 1 of 5"
End Sub

vba messagebox okonly

Important! You must remember to surround your text with quotations.

MessageBox LineBreaks

You can also add line breaks to your message box prompts with ‘vbNewLine’.

Sub MsgBoxPromptTitle_NewLine()
  MsgBox "Step 1 Complete." & vbNewLine & "Click OK to Run Step 2.", , "Step 1 of 5"
End Sub

vba messagebox insert line

Notice we use the & symbol to join text together. You can learn more about using & with text and other options for inserting linebreaks in our article on joining text.

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

MsgBox Icons

VBA gives you the ability to add one of four pre-built icons to your message boxes:

Icon Constant Icon
vbInformation vba information msgbox icon
vbCritical vba critical msgbox icon
vbQuestion vba question msgbox icon
vbExclamation vba exclamation msgbox icon

The Icon constant should be placed within the button argument:

Sub MsgBoxQuestionIcon()
  MsgBox "Question Example", vbQuestion
End Sub

This will generate the default ‘OK’ message box with the Question icon:

vba msgbox icon

Notice how when you type, the VBA Editor will show you the options available to you:

vba msgbox syntax

This is helpful because you don’t need to remember the exact syntax or names of icons or buttons.

Now we will demo each message box icon:

MsgBox Icons – Information

Sub MsgBoxInformationIcon()
  MsgBox "Information Example", vbInformation
End Sub

vba msgbox information

MsgBox Icons – Critical

Sub MsgBoxCriticalIcon()
  MsgBox "Critical Example", vbCritical
End Sub

vba critical message box

VBA Programming | Code Generator does work for you!

MsgBox Icons – Question

Sub MsgBoxQuestionIcon()
  MsgBox "Question Example", vbQuestion
End Sub

vba msgbox icon

MsgBox Icons – Exclamation

Sub MsgBoxExclamationIcon()
  MsgBox "Exclamation Example", vbExclamation
End Sub

msgbox exclamation icon

Below we will talk about generating message boxes with different button layouts. If you do choose a different message box type, you will need to append the icon type after the buttons using a “+”:

Sub MsgBoxQuestionIcon()
  MsgBox "Do you want to continue?", vbOKCancel + vbQuestion
End Sub

vba messagebox question

MsgBox Variables

So far we have worked primarily with the default ‘OK’ message box. The OK message box only has one option: Pressing ‘OK’ allows the code to continue.  However, you can also specify other button groupings: OK / Cancel, Yes / No, etc.

In which case you will want to perform different actions based on which button is pressed.  Let’s look at an example.

Here is the message box we will generate:

vba yes no msgbox

This is the entire code (we will break it down next):

Sub MsgBoxVariable()

Dim answer As Integer
answer = MsgBox("Do you want to Continue?", vbQuestion + vbYesNo)

  If answer = vbYes Then
    MsgBox "Yes"
  Else
    MsgBox "No"
  End If

End Sub

First we assign the messagebox output to an integer variable.

Dim answer As Integer

answer = MsgBox("Do you want to Continue?", vbQuestion + vbYesNo)

Next we use an If-Else to determine what to do based on which button is pressed:

If answer = vbYes Then
  MsgBox "Yes"
Else
  MsgBox "No"
End If

The MsgBox function returns an integer value (between 1-7) so we define the variable as an integer type.  However, instead of referring to the integer number, you can refer to a constant (ex. vbOK, vbCancel, etc.).  Look at this table to see all of the options:

Button Constant Value
OK vbOK 1
Cancel vbCancel 2
Abort vbAbort 3
Retry vbRetry 4
Ignore vbIgnore 5
Yes vbYes 6
No vbNo 7

Now we will demo each button grouping:

OK Message Box – vbOKOnly

messagebox okonly

This is the standard VBA messagebox.

Sub MsgBox_OKOnly()

Dim answer As Integer
answer = MsgBox("OKOnly Example", vbOKOnly)

End Sub

OK Cancel Message Box – vbOKCancel

messagebox okcancel

Sub MsgBox_OKCancel()

Dim answer As Integer
answer = MsgBox("OK Cancel Example", vbOKCancel)

  If answer = vbOK Then
    MsgBox "OK"
  Else
    MsgBox "Cancel"
  End If

End Sub

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

Yes No Message Box – vbYesNo

messagebox yes no

Sub MsgBox_YesNo()

Dim answer As Integer
answer = MsgBox("Yes No Example", vbYesNo)

  If answer = vbYes Then
    MsgBox "Yes"
  Else
    MsgBox "No"
  End If

End Sub

Yes No Cancel Message Box – vbYesNoCancel

messagebox yes no cancel

Sub MsgBox_YesNoCancel()

Dim answer As Integer
answer = MsgBox("Yes No Cancel Example", vbYesNoCancel)

  If answer = vbYes Then
    MsgBox "Yes"
  ElseIf answer = vbNo Then
    MsgBox "No"
  Else
    MsgBox "Cancel"
  End If

End Sub

Abort Retry Ignore Message Box – vbAbortRetryIgnore

messagebox abort retry ignore

Sub MsgBox_AbortRetryIgnore()

Dim answer As Integer
answer = MsgBox("Abort Retry Ignore Example", vbAbortRetryIgnore)

  If answer = vbAbort Then
    MsgBox "Abort"
  ElseIf answer = vbRetry Then
    MsgBox "Retry"
  Else
    MsgBox "Ignore"
  End If

End Sub

Retry Cancel Message Box – vbRetryCancel

messagebox retry cancel

Sub MsgBox_RetryCancel()

Dim answer As Integer
answer = MsgBox("Retry Cancel Example", vbRetryCancel)

  If answer = vbRetry Then
    MsgBox "Retry"
  Else
    MsgBox "Cancel"
  End If

End Sub

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

VBA MessageBox Examples

Message Box Confirmation Before Running Macro

This code will display a Yes No Message box before calling a macro. If Yes is clicked the macro is called, if No is clicked, the Macro does not run.

Sub Msgbox_BeforeRunning()

  Dim answer As Integer
  answer = MsgBox("Do you want to run Macro1?", vbQuestion + vbYesNo)

  If answer = vbYes Then Call Macro1

End Sub

vba confirmation box run macro

Yes / No Message Box – Exit Sub

Here we will confirm with the user whether to continue running a macro. If No is clicked, the code will exit the sub, otherwise the procedure will continue.

Sub Msgbox_BeforeRunning()

  Dim answer As Integer
  answer = MsgBox("Do you want to continue?", vbQuestion + vbYesNo)

  If answer = vbNo Then Exit Sub
  
  'Some Code

End Sub

vba yes no exit sub

VBA Message Box in Access VBA

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

vba yes no msgbox

In VBA, using the message box, we can create a yes no msgbox, used to record user input based on clicking yes or no. The syntax to make a yes-no message box is as follows variable = MsgBox(“Text”, vbQuestion + vbYesNo + vbDefaultButton2, “Message Box Title”) where one must declare variable as an integer.

In VBA coding, we often need to collect the input values from the users to perform some tasks. One of such tasks is collecting the users’ yes or no responses. By using VBA MsgBox Yes No method, we can write the code to proceed further in the code.

In certain situations, we may need to present a “Yes” or “No” option in front of the user to give their response based on them. Then, we can run the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more.

For example, look at the below image of the MsgBox in VBAVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.

VBA Message Box Continue.png

If the user says Yes, “we can write code to perform a specific task,” and if the user says “No,” we can write code to perform another set of tasks.

Table of contents
  • Excel VBA MsgBox (Yes/No)
    • How to Work with MsgBox Yes/No Response?
      • Example #1 – Copy and Paste based on Response
      • Example #2 – Hide & Unhide Sheets Based on the Response
    • Recommended Articles

How to Work with MsgBox Yes/No Response?

You can download this VBA Message Box Yes or No Excel Template here – VBA Message Box Yes or No Excel Template

Example #1 – Copy and Paste based on Response

Look at the below code.

Code:

Sub MessageBox_Yes_NO_Example1()

 Dim AnswerYes As String
 Dim AnswerNo As String

 AnswerYes = MsgBox("Do you Wish to Copy?", vbQuestion + vbYesNo, "User Repsonse")

 If AnswerYes = vbYes Then
   Range("A1:A2").Copy Range("C1")
 Else
   Range("A1:A2").Copy Range("E1")
 End If

End Sub

VBA Message box Example 1

Explanation:

The above has declared the variable as String i.e.

Dim AnswerYes As String

In the next line, we have assigned the value through a message box asking, “Do you wish to copy?”.

AnswerYes = MsgBox("Do You Wish to Copy?", vbQuestion + vbYesNo, "User Repsonse")

Now, the IF statement evaluates the response given through the message box. For example, if the message box result is vbYes, it will copy the range A1 to A2 and paste it into cell C1.

   If AnswerYes = vbYes Then
      Range("A1:A2").Copy Range("C1")

If the response given by the message box is No, then it will copy the range A1 to A2 and paste it into cell E1.

Else
Range("A1:A2").Copy Range("E1")
End If

We have entered a few values in cells A1 and A2 now.

VBA Message box Example 1-1

Now, we will run the code using the F5 key, or through the run option, a message box will appear in front of us and ask for our response.

VBA Message box Example 1-2

If we click “Yes,” it will copy the range A1 to A2 and paste it into the C1 cell. Now, we will click on “Yes” and see the result.

VBA Message box Example 1-3

So, it has performed the task assigned if the response is YES.

Now again, we will run the code.

yes or no Example 1-4

This time we will select No and see what happens.

yes or no Example 1-5

Yes, it performed the task assigned in the code i.e.

Else
Range("A1:A2").Copy Range("E1")

Example #2 – Hide & Unhide Sheets Based on the Response

The below code will hide all the sheets except the active sheet if the response is yes.

Code:

Sub HideAll()

  Dim Answer As String
  Dim Ws As Worksheet

  Answer = MsgBox("Do you Wish to Hide All?", vbQuestion + vbYesNo, "Hide")
  
  If Answer = vbYes Then

    For Each Ws In ActiveWorkbook.Worksheets
     If Ws.Name <> ActiveSheet.Name Then Ws.Visible = xlSheetVeryHidden
    Next Ws

   ElseIf Answer = vbNo Then MsgBox "You have selected not to hide the sheets", vbInformation, "No Hide"
   End If

End Sub

The above code will hide all the worksheets except the sheet we are in right now if the response from the message box is YES.

yes or no Example 2

If the response from the message box is NO, it will display the message box saying, “You have selected not to hide the sheets.”

yes or no Example 1-6

Similarly, the below code will unhide the sheet if the response is Yes.

Code:

Sub UnHideAll()

  Dim Answer As String
  Dim Ws As Worksheet
 
  Answer = MsgBox("Do you Wish to Unhide All?", vbQuestion + vbYesNo, "Hide")

  If Answer = vbYes Then

    For Each Ws In ActiveWorkbook.Worksheets
       Ws.Visible = xlSheetVeryHidden
  Next Ws

 ElseIf Answer = vbNo Then MsgBox "You have selected not to Unhide the sheets", vbInformation, "No Hide"
 End If

End Sub

It works the same as the hide sheet code. If yes, it will unhide. If not, it will not unhide.

Recommended Articles

This article has been a guide to VBA Message Box. Here, we discuss creating a Yes or No response in the Excel VBA using MsgBox, practical examples, and a downloadable Excel template. Below you can find some useful Excel VBA articles: –

  • VBA Find Next
  • VBA ISERROR
  • VBA Collection Object
  • VBA Text Function
  • VBA Save As

Использование функции MsgBox в VBA Excel, ее синтаксис и параметры. Значения, возвращаемые функцией MsgBox. Примеры использования.

Функция MsgBox предназначена в VBA Excel для вывода сообщения в диалоговом окне, ожидания нажатия кнопки и возврата значения типа Integer, указывающего на то, какая кнопка была нажата. Для упрощения восприятия информации, в этой статье не рассматриваются параметры, связанные с контекстной справкой и модальностью диалогового окна MsgBox.

Синтаксис функции

MsgBox ( Prompt [, Buttons ] [, Title ])

Обязательным параметром функции MsgBox является Prompt, если Buttons и Title явно не указаны, используются их значения по умолчанию. Кроме того, если необязательные параметры не указаны и возвращаемое значение не присваивается переменной, сообщение не заключается в скобки:

Пример 1

Sub Test1()

MsgBox «Очень важное сообщение!»

End Sub

Параметры функции

Параметр Описание Значение
по умолчанию
Prompt* Обязательный параметр. Выражение типа String, отображаемое в диалоговом окне в виде сообщения. Разделить на строки можно с помощью константы vbNewLine. Нет
Buttons Необязательный параметр. Числовое выражение, которое представляет собой сумму значений, задающих номер и тип отображаемых кнопок, стиль используемого значка, тип кнопки по умолчанию. 0
Title Необязательный параметр. Выражение типа String, отображаемое в заголовке диалогового окна. Имя приложения**

*Максимальная длина параметра Prompt составляет примерно 1024 знака и зависит от их ширины.

**В Excel по умолчанию в заголовке MsgBox выводится надпись «Microsoft Excel».

Константы параметра «Buttons»

Тип и количество кнопок

Константа Описание Значение
vbOKOnly Отображается только кнопка OK. 0
vbOKCancel Отображаются кнопки OK и Cancel (Отмена). 1
vbAbortRetryIgnore Отображаются кнопки Abort (Прервать), Retry (Повторить) и Ignore (Пропустить). 2
vbYesNoCancel Отображаются кнопки Yes (Да), No (Нет) и Cancel (Отмена). 3
vbYesNo Отображаются кнопки Yes (Да) и No (Нет). 4
vbRetryCancel Отображаются кнопки Retry (Повторить) и Cancel (Отмена). 5

Стиль значка

Константа Описание Значение
vbCritical Отображается значок Critical — Критичное сообщение, сообщение об ошибке. 16
vbQuestion Отображается значок Question — Сообщение с вопросом. 32
vbExclamation Отображается значок Exclamation — Предупреждающее сообщение. 48
vbInformation Отображается значок Information — Информационное сообщение. 64

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

Пример 2

Sub Test2()

Dim a As Integer

a = MsgBox(«Критичное сообщение, сообщение об ошибке», 16)

a = MsgBox(«Сообщение с вопросом», 32)

a = MsgBox(«Предупреждающее сообщение», 48)

a = MsgBox(«Информационное сообщение», 64)

End Sub

Кнопка по умолчанию

Константа Описание Значение
vbDefaultButton1 По умолчанию активна первая кнопка. 0
vbDefaultButton2 По умолчанию активна вторая кнопка. 256
vbDefaultButton3 По умолчанию активна третья кнопка. 512

Возвращаемые значения

Константа Кнопка Значение
vbOK OK 1
vbCancel Отмена 2
vbAbort Прервать 3
vbRetry Повторить 4
vbIgnore Пропустить 5
vbYes Да 6
vbNo Нет 7

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

Для третьего примера зададим следующие параметры первой функции MsgBox:

  • Prompt = «Выберите кнопку!»
  • Buttons = 323 (3 (vbYesNoCancel) + 64 (vbInformation) + 256 (vbDefaultButton2))
  • Title = «Выбор кнопки»

Вторая функция MsgBox используется как простое информационное сообщение с параметрами по умолчанию.

Пример 3

Sub Test3()

Dim a As Integer

a = MsgBox(«Выберите кнопку!», 323, «Выбор кнопки»)

If a = 6 Then

MsgBox «Вы нажали кнопку: Да»

ElseIf a = 7 Then

MsgBox «Вы нажали кнопку: Нет»

Else

MsgBox «Вы нажали кнопку: Отмена»

End If

End Sub

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

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

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

Понравилась статья? Поделить с друзьями:
  • Excel vba next do you
  • Excel vba instr пример
  • Excel vba name of named range
  • Excel vba instr без учета регистра
  • Excel vba name list