Msgbox что это
Перейти к содержимому

Msgbox что это

  • автор:

VBA MsgBox

VBA MsgBox is the Pop up Box function to display a message in VBA Language. VBA MsgBox Function helps to display any value to the user with the given prompt. Message Box in VBA is available in all MS Office Application to show the value of a variable or a given string and wait for user to click the buttons. Use the MsgBox to display a Message Box in Excel, Access, Word, PowerPoint (PPT) and Outlook.

Syntax of VBA MsgBox Function

Following is the syntax of the VBA MsgBox Function. Message Box function has one required parameter and four optional parameters.

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

Parameters

MsgBox Function takes the following named arguments. We can pass the values to the MsgBox Function based on our requirement. MsgBox Function will process the given arguments values and shows the pop up box. We can pass the prompt and title as string values, and we can provide the button values from the predefined constants.

  • prompt : Message which you wants to show in the message box body. Prompt is the required parameter,we must pass an argument value to the message box prompt parameter.
  • buttons : We can change the default buttons and style of the message box using the button parameters. VBA MsgBox Function has the predefined list of the constants to set the button styles. This is an optional parameter, the default value of the buttons is vbOKOnly. This will show the message box with simple OK button.
  • title : We can provide the title of the message box window using Title parameter. This is an optional parameter, the default title of the message box is the name of the Application.
  • helpfile : helpfile parameter is useful to set the context-sensitive identifier. This is an optional parameter, context parameter is required when you provide helpfile parameter.
  • context : to prove the context number set to the given help topic. This is an optional parameter, helpfile parameter is required when you provide context parameter.

Button Options

We can pass the button following constant to VBA MsgBox function to can change the default buttons. Here are list of predefined button constants and its values. We can provide the VBA MsgBox constants or respective ENUM value.

Constant Value Description
vbOKOnly 0 This is the default value of the button parameter. You can provide vbOKOnly constant to display OK button only.
vbOKCancel 1 You can provide vbOKCancel constant to display OK and Cancel buttons.
vbAbortRetryIgnore 2 You can provide vbAbortRetryIgnore constant to display Abort, Retry, and Ignore buttons.
vbYesNoCancel 3 You can provide vbYesNoCancel constant to display Yes, No, and Cancel buttons.
vbYesNo 4 You can provide vbYesNo constant to display Yes and No buttons.
vbRetryCancel 5 You can provide vbRetryCancel constant to display Retry and Cancel buttons.

Syntax:

MsgBox prompt:=”Your Prompt”, Buttons:=vbOKCancel

Icon Styles

Following are predefined constants to add an icon to the message box. We can provide the icons constant along with the button constant (0-5) which are listed above.

Constant Value Description
vbCritical 16 vbCritical constants uses to display Critical Message icon.
vbQuestion 32 vbQuestion constants uses to display Warning Message icon.
vbExclamation 48 vbExclamation constants uses to display Warning Message icon.
vbInformation 64 vbInformation constants uses to display Information Message icon.

MsgBox “Your Prompt”, vbInformation + vbOKCancel

Default Buttons

We can also set the default button of the message box. We can mention focused button to be clicked when uses press the enter button.

Constant Value Description
vbDefaultButton1 0 vbDefaultButton1 will set the First button is default.
vbDefaultButton2 256 vbDefaultButton2 will set the Second button is default.
vbDefaultButton3 512 vbDefaultButton3 will set the Third button is default.
vbDefaultButton4 768 vbDefaultButton4 will set the Fourth button is default.

Syntax:

MsgBox “Your Prompt”, vbInformation + vbOKCancel + vbDefaultButton2

Modality, Foreground and Right Alignment

Here are the constants to set the advanced options of the message box. These options helps to determine the modality of the message box and change the alignment of the body text.

Constant Value Description
vbApplicationModal 0 When you set vbApplicationModal option, you must respond to the message box before continuing work in the current application.
vbSystemModal 4096 When you set vbSystemModal option, all of your applications are suspended until you responds to the message box.
vbMsgBoxHelpButton 16384 vbMsgBoxHelpButton uses to add Help button to the message box.
vbMsgBoxSetForeground 65536 We can set the message box window as the foreground window using vbMsgBoxSetForeground.
vbMsgBoxRight 524288 Using vbMsgBoxRight, You can make the text of message box right-aligned.
vbMsgBoxRtlReading 1048576 vbMsgBoxRtlReading helps to set text appearance as right-to-left reading on Hebrew and Arabic system users.

VBA-MsgBox-Modal-Help-and-Right-Alignment

Syntax:

MsgBox “Your Prompt”, vbInformation + vbOKCancel + vbMsgBoxHelpButton + vbMsgBoxRight

Return Values

We can capture the return value of the message box and check using the following constants.

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

VBA-MsgBox-Return-Values

Syntax:

If MsgBox(“Do you wants to continue”, vbInformation + vbYesNo) = vbYes Then
MsgBox “You pressed Yes button”
End If

Examples:

Here are the list of most frequently used examples on VBA MsgBox Function. You can have a look to understand the concepts with suitable examples.

Example to set VBA Buttons:

The following example shows a message box with OK and Cancel buttons.

Example to Change VBA Icon:

Here is a simple example to show a message box with vbInformation Icon and OK and Cancel buttons.

Example to Set VBA Default Button:

The below example sets the second button as default button. We can set any of the four button as default button using the given constants or Enumeration values.

Example to Set VBA Default Button:

The following example will show you the help button in message box. and the text is right-aligned

Example to Return User Selection:

This example will ask the user to press one of the buttons and show the second message based on the return value of the first message box.

VBA MsgBox

The MsgBox function shows a popup with a message, buttons, and an icon. Different arguments can be provided to the Buttons argument to show different buttons and icons. The MsgBox function returns a member of the VbMsgBoxResult enum which indicates which button was pushed by the user.

Syntax:

MsgBox(Prompt,[Buttons As VbMsgBoxStyle=vbOKOnly],[Title],[HelpFile],[Context]) As VbMsgBoxResult

VbMsgBoxStyle

The Buttons parameter of the MsgBox function can be passed constants from the VbMsgBoxStyle enum which determine which type of buttons and icon the message box will have. A button style can be joined with an icon style by adding the constants together.

MsgBox Hello World

Constant Value Description
vbOKOnly 0 OK button only
vbOKCancel 1 OK and Cancel buttons
vbAbortRetryIgnore 2 Abort, Retry, and Ignore buttons
vbYesNoCancel 3 Yes, No, and Cancel buttons
vbYesNo 4 Yes and No buttons
vbRetryCancel 5 Retry and Cancel buttons
vbCritical 16 Critical Message icon (Red «x» circle)
vbQuestion 32 Warning Query icon (Blue «?» circle)
vbExclamation 48 Warning Message icon (Yellow «!» triangle)
vbInformation 64 Information Message icon (Blue «i» circle)
vbDefaultButton1 0 First button is default
vbDefaultButton2 256 Second button is default
vbDefaultButton3 512 Third button is default
vbDefaultButton4 768 Fourth button is default
vbApplicationModal 0 The application is suspended until the message box is dismissed
vbSystemModal 4096 All applications are suspended until the message box is dismissed
vbMsgBoxHelpButton 16384 Help button is added to the message box
vbMsgBoxSetForeground 65536 Sets the message box window as the foreground window
vbMsgBoxRight 524288 Right-aligns text
vbMsgBoxRtlReading 1048576 Specifies right-to-left reading on Hebrew and Arabic systems

VbMsgBoxResult

The MsgBox function returns a value from the VbMsgBoxResult enum which represents the button clicked by the user.

MsgBox Yes No

Constant Value
vbOK 1
vbCancel 2
vbAbort 3
vbRetry 4
vbIgnore 5
vbYes 6
vbNo 7

Copyright © 2021 ‐ 2023 Code Planet LLC. All Rights Reserved.

VBA MsgBox Function

In VBA, the dialog box can be created by using the MsgBox function. The MsgBox enables creating dialog boxes with many options.

For interacting with the users of your application, you may create dialog boxes. In VBA, a dialog box can be created by using the MsgBox function.

The MsgBox enables the creation of dialog boxes with many options. For example, a dialog box is displayed before quitting the application. In that case, you may ask the user “Are you sure you want to quit?” with Yes and No options.

Similarly, before performing a critical operation like deleting records, a dialog box appears confirming the user with a message and OK/Cancel options.

You may set all these options (Yes/No, OK/Cancel etc.) along with the message displayed to the user by using MsgBox function.

Syntax of MsgBox in VBA

For creating a dialog, the general syntax is:

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

These arguments for MsgBox are explained below:

  • prompt – This is the only required argument. The prompt is a string that appears to the user. For example, “Are you Sure?”. You may display any message there as per the requirement. However, the length of the message is limited –around 1024 characters. The limit also depends on the character width e.g. capital letters may take more space than small letters. The carriage return character (Chr(13)) can be used for adding lines in the dialog box message.
  • Button – This is an optional argument. If you do not provide a value, the default is taken, which is 0. That is, the dialog appears with ‘Ok’ button only.
  • Title – This specifies the message that appears in the title bar of the message box. If not provided, the default is the application name.
  • helpfile – used to provide context-sensitive help. If you provide the helpfile then context is also required.
  • context – The context in relation to the helpfile. This is a numeric expression.

An example of simple MsgBox VBA

The first example simply displays the message in a dialog box with ‘Ok’ button. For that, just enclose the message without specifying a button, so the default is taken. Have a look at the code:

MsgBox

В Excel VBA вы можете использовать функцию MsgBox для отображения окна сообщения (как показано ниже):

Default message in a VBA Msgbox

MsgBox — это не что иное, как диалоговое окно, которое вы можете использовать для информирования своих пользователей, показывая пользовательское сообщение или получая некоторые основные входные данные (такие как Да / Нет или OK / Отмена).

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

Примечание: в этом уроке я буду использовать слова «окно сообщения» и MsgBox взаимозаменяемо. При работе с Excel VBA вам всегда нужно использовать MsgBox.

Анатомия VBA MsgBox в Excel

Окно сообщения состоит из следующих частей:

  1. Title — заголовок: обычно используется для отображения содержания окна сообщения. Если вы ничего не указали, отображается имя приложения, в данном случае Microsoft Excel.
  2. Prompt — подсказка: это сообщение, которое вы хотите отобразить. Вы можете использовать это пространство, чтобы написать пару строк или даже отобразить таблицы / данные здесь.
  3. Button(s) — кнопка(-и): хотя кнопка «ОК» является кнопкой по умолчанию, ее можно настроить таким образом, чтобы отображать такие кнопки, как «Да / Нет»; «Да / Нет / Отмена», «Повторить» / «Пропустить» и т.д.
  4. Close Icon — значок закрытия: Вы можете закрыть окно сообщения, нажав на значок закрытия.

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

Как я уже упоминал, MsgBox является функцией и имеет синтаксис, аналогичный другим функциям VBA.

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

  • prompt — это обязательный аргумент. Он отображает сообщение, которое вы видите в MsgBox. В нашем примере текст «Это образец MsgBox» — это «подсказка». В приглашении можно использовать до 1024 символов, а также использовать его для отображения значений переменных. Если вы хотите показать подсказку, состоящую из нескольких строк, вы можете сделать это также (подробнее об этом позже в этом руководстве).
  • [buttons ] — определяет, какие кнопки и значки отображаются в MsgBox. Например, если я использую vbOkOnly, на нем будет отображаться только кнопка OK, а если я использую vbOKCancel, на нем будут отображаться кнопки OK и Отмена. Я расскажу о различных видах кнопок позже в этом уроке.
  • [title] — здесь вы можете указать заголовок в диалоговом окне сообщения. Отображается в строке заголовка MsgBox. Если вы ничего не укажете, будет показано название приложения.
  • [helpfile] — вы можете указать файл справки, к которому можно получить доступ, когда пользователь нажимает кнопку «Справка». Кнопка справки появится только тогда, когда вы используете для нее код кнопки. Если вы используете файл справки, вам также необходимо указать аргумент context.
  • [context] — это числовое выражение, которое является номером контекста справки, назначенным соответствующему разделу справки.

Если вы новичок в концепции Msgbox, не стесняйтесь игнорировать аргументы [helpfile] и [context]. Они редко используются.

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

Константы кнопки Excel VBA MsgBox (примеры)

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

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

Константа кнопки Описание
vbOKOnly Показывает только кнопку ОК
vbOKCancel Показывает кнопки ОК и Отмена
vbAbortRetryIgnore Показывает кнопки «Прервать», «Повторить» и «Игнорировать»
vbYesNo Показывает кнопки Да и Нет
vbYesNoCancel Показывает кнопки Да, Нет и
Отмена
vbRetryCancel Показывает кнопки «Повторить» и «Отменить»
vbMsgBoxHelpButton Показывает кнопку справки. Чтобы это работало, вам нужно
использовать аргументы
справки и контекста в функции MsgBox
vbDefaultButton1 Делает первую кнопку по
умолчанию. Вы можете
изменить номер, чтобы
изменить кнопку по
умолчанию. Например,
vbDefaultButton2 делает вторую
кнопку по умолчанию

Примечание. Просматривая примеры создания различных кнопок, вы можете задаться вопросом, какой смысл использовать эти кнопки, если они не влияют на код.
Влияют! В зависимости от выбора вы можете кодировать то, что вы хотите, чтобы код делал. Например, если вы выберете «ОК», код должен продолжиться, а если вы нажмете «Отмена», код должен прекратиться. Это можно сделать с помощью переменных и присвоения значения окна сообщения переменной. Мы рассмотрим это в последующих разделах этого урока.

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

Кнопки MsgBox — vbOKOnly (по умолчанию)

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

Sample message box

Ниже приведен код, который выдаст это окно сообщения:

Обратите внимание, что текстовая строка должна быть в двойных кавычках.

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

Кнопки MsgBox — ОК и Отмена

Если вы хотите показать только ОК и кнопку Отмена, вам нужно использовать константу vbOKCancel

ok and cancel buttons in a message box

Кнопки MsgBox — Отмена, Повтор и Игнорирование

Вы можете использовать константу vbAbortRetryIgnore для отображения кнопок «Отмена», «Повторить» и «Игнорировать».

Excel VBA Msgbox - Abort Retry and Cancel buttons

Кнопки MsgBox — Да и Нет

Вы можете использовать константу vbYesNo для отображения кнопок Да и Нет.

Yes and No buttons in a message box

Кнопки MsgBox — Да, Нет и Отмена

Вы можете использовать константу vbYesNoCancel для отображения кнопок «Да», «Нет» и «Отмена».

Excel VBA Message Box- Yes and No and Cancel

Кнопки MsgBox — повторить попытку и отменить

Вы можете использовать константу vbRetryCancel для отображения кнопок «Повторить» и «Отмена».

Retry and Cancel buttons

Кнопки MsgBox — Кнопка справки

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

help button in the message box dialog box

Обратите внимание, что в этом коде мы объединили две разные константы кнопки (vbRetryCancel + vbMsgBoxHelpButton). Первая часть показывает кнопки «Повторить» и «Отмена», а вторая часть показывает кнопку «Справка».

MsgBox Buttons — Настройка кнопки по умолчанию

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

Ниже приведен код, который установит в качестве кнопки по умолчанию вторую кнопку (кнопка «Нет»).

by default, second button is selected

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

Константы значков Excel VBA MsgBox (примеры)

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

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

Константа значка Описание
vbCritical Показывает значок критического сообщения
vbQuestion Показывает значок вопроса
vbExclamation Показывает значок предупреждения
vbInformation Показывает значок информации

Иконки MsgBox — Критические

Если вы хотите показать критический значок в своем MsgBox, используйте константу vbCritical. Вы можете использовать ее вместе с другими константами кнопки (поставив знак + между кодами).

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

Excel VBA Msgbox - critical icon

Если вы хотите показать критический значок с кнопками Да и Нет, используйте следующий код:

Excel VBA Msgbox - critical icon YesNO

Иконки MsgBox — Вопрос

Если вы хотите показать иконку вопроса в своем MsgBox, используйте константу vbQuestion.

Excel VBA Msgbox - question icon

Иконки MsgBox — Восклицательный знак

Если вы хотите показать восклицательный значок в вашем MsgBox, используйте константу vbExclamation.

Excel VBA Msgbox - exclamation icon

Иконки MsgBox — Информация

Если вы хотите отобразить информационный значок в вашем MsgBox, используйте константу vbInformation.

Excel VBA Msgbox - information

Настройка заголовка и приглашения в MsgBox

При использовании MsgBox вы можете настроить заголовок и сообщения подсказок.

До сих пор в примерах, которые мы видели, использовался Microsoft Excel в качестве заголовка. Если вы не указали аргумент title, MsgBox автоматически использует заголовок приложения (в данном случае это был Microsoft Excel).

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

Excel VBA Msgbox - title

Точно так же вы также можете настроить сообщение подсказки.

Excel VBA Msgbox - prompt

Вы также можете добавить разрывы строк в сообщении подсказки.

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

Excel VBA Msgbox - vbnewline

Вы также можете использовать символ возврата каретки — Chr (13) или перевод строки — Chr (10), чтобы вставить новую строку в сообщение с подсказкой.

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

Присвоение значения MsgBox переменной

До сих пор мы видели примеры, где мы создавали окна сообщений и настраивали кнопки, значки, заголовок и приглашение.

Однако нажатие кнопки ничего не сделало.

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

Поэтому, если я нажимаю кнопку «Да», функция MsgBox возвращает значение (6 или константа vbYes), которое я могу использовать в своем коде. Аналогично, если пользователь выбирает кнопку «Нет», он возвращает другое значение ((7 или константа vbNo)), которое я могу использовать в коде.

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

При нажатии кнопки Константа Значение
Ok vbOk 1
Cancel vbCancel 2
Abort vbAbort 3
Retry vbRetry 4
Ignore vbIgnore 5
Yes vbYes 6
No vbNo 7

Теперь давайте посмотрим, как мы можем контролировать макрос-код VBA в зависимости от того, на какую кнопку нажимает пользователь.

В приведенном ниже коде, если пользователь нажимает кнопку «Да», отображается сообщение «Вы нажали кнопку «Да», а если пользователь нажимает кнопку «Нет», отображается сообщение «Вы нажали кнопку «Нет»».

В приведенном выше коде я присвоил значение функции MsgBox переменной Result. Когда вы нажимаете кнопку «Да», переменная Result получает константу vbYes (или число 6), а когда вы нажимаете «Нет», переменная Result получает константу vbNo (или число 7).

Затем я использовал конструкцию If Then Else, чтобы проверить, содержит ли переменная Result значение vbYes. Если это так, отображается запрос «Вы нажали Да», в противном случае — «Вы нажали Нет».

Вы можете использовать ту же концепцию для запуска кода, если пользователь нажимает Да, и выход из подпрограммы, когда он нажимает Нет.

Примечание. Когда вы присваиваете выход MsgBox переменной, вы должны поместить аргументы функции MsgBox в круглые скобки. Например, в строке Result = MsgBox («Хотите продолжить?», VbYesNo + vbQuestion) вы можете видеть, что аргументы находятся в скобках.

Если вы хотите в дальнейшем углубиться в функцию Message Box, вот официальный документ по ней.

MsgBox

В Excel VBA вы можете использовать функцию MsgBox для отображения окна сообщения (как показано ниже):

Default message in a VBA Msgbox

MsgBox — это не что иное, как диалоговое окно, которое вы можете использовать для информирования своих пользователей, показывая пользовательское сообщение или получая некоторые основные входные данные (такие как Да / Нет или OK / Отмена).

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

Примечание: в этом уроке я буду использовать слова «окно сообщения» и MsgBox взаимозаменяемо. При работе с Excel VBA вам всегда нужно использовать MsgBox.

Анатомия VBA MsgBox в Excel

Окно сообщения состоит из следующих частей:

  1. Title — заголовок: обычно используется для отображения содержания окна сообщения. Если вы ничего не указали, отображается имя приложения, в данном случае Microsoft Excel.
  2. Prompt — подсказка: это сообщение, которое вы хотите отобразить. Вы можете использовать это пространство, чтобы написать пару строк или даже отобразить таблицы / данные здесь.
  3. Button(s) — кнопка(-и): хотя кнопка «ОК» является кнопкой по умолчанию, ее можно настроить таким образом, чтобы отображать такие кнопки, как «Да / Нет»; «Да / Нет / Отмена», «Повторить» / «Пропустить» и т.д.
  4. Close Icon — значок закрытия: Вы можете закрыть окно сообщения, нажав на значок закрытия.

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

Как я уже упоминал, MsgBox является функцией и имеет синтаксис, аналогичный другим функциям VBA.

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

  • prompt — это обязательный аргумент. Он отображает сообщение, которое вы видите в MsgBox. В нашем примере текст «Это образец MsgBox» — это «подсказка». В приглашении можно использовать до 1024 символов, а также использовать его для отображения значений переменных. Если вы хотите показать подсказку, состоящую из нескольких строк, вы можете сделать это также (подробнее об этом позже в этом руководстве).
  • [buttons ] — определяет, какие кнопки и значки отображаются в MsgBox. Например, если я использую vbOkOnly, на нем будет отображаться только кнопка OK, а если я использую vbOKCancel, на нем будут отображаться кнопки OK и Отмена. Я расскажу о различных видах кнопок позже в этом уроке.
  • [title] — здесь вы можете указать заголовок в диалоговом окне сообщения. Отображается в строке заголовка MsgBox. Если вы ничего не укажете, будет показано название приложения.
  • [helpfile] — вы можете указать файл справки, к которому можно получить доступ, когда пользователь нажимает кнопку «Справка». Кнопка справки появится только тогда, когда вы используете для нее код кнопки. Если вы используете файл справки, вам также необходимо указать аргумент context.
  • [context] — это числовое выражение, которое является номером контекста справки, назначенным соответствующему разделу справки.

Если вы новичок в концепции Msgbox, не стесняйтесь игнорировать аргументы [helpfile] и [context]. Они редко используются.

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

Константы кнопки Excel VBA MsgBox (примеры)

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

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

Константа кнопки Описание
vbOKOnly Показывает только кнопку ОК
vbOKCancel Показывает кнопки ОК и Отмена
vbAbortRetryIgnore Показывает кнопки «Прервать», «Повторить» и «Игнорировать»
vbYesNo Показывает кнопки Да и Нет
vbYesNoCancel Показывает кнопки Да, Нет и
Отмена
vbRetryCancel Показывает кнопки «Повторить» и «Отменить»
vbMsgBoxHelpButton Показывает кнопку справки. Чтобы это работало, вам нужно
использовать аргументы
справки и контекста в функции MsgBox
vbDefaultButton1 Делает первую кнопку по
умолчанию. Вы можете
изменить номер, чтобы
изменить кнопку по
умолчанию. Например,
vbDefaultButton2 делает вторую
кнопку по умолчанию

Примечание. Просматривая примеры создания различных кнопок, вы можете задаться вопросом, какой смысл использовать эти кнопки, если они не влияют на код.
Влияют! В зависимости от выбора вы можете кодировать то, что вы хотите, чтобы код делал. Например, если вы выберете «ОК», код должен продолжиться, а если вы нажмете «Отмена», код должен прекратиться. Это можно сделать с помощью переменных и присвоения значения окна сообщения переменной. Мы рассмотрим это в последующих разделах этого урока.

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

Кнопки MsgBox — vbOKOnly (по умолчанию)

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

Sample message box

Ниже приведен код, который выдаст это окно сообщения:

Обратите внимание, что текстовая строка должна быть в двойных кавычках.

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

Кнопки MsgBox — ОК и Отмена

Если вы хотите показать только ОК и кнопку Отмена, вам нужно использовать константу vbOKCancel

ok and cancel buttons in a message box

Кнопки MsgBox — Отмена, Повтор и Игнорирование

Вы можете использовать константу vbAbortRetryIgnore для отображения кнопок «Отмена», «Повторить» и «Игнорировать».

Excel VBA Msgbox - Abort Retry and Cancel buttons

Кнопки MsgBox — Да и Нет

Вы можете использовать константу vbYesNo для отображения кнопок Да и Нет.

Yes and No buttons in a message box

Кнопки MsgBox — Да, Нет и Отмена

Вы можете использовать константу vbYesNoCancel для отображения кнопок «Да», «Нет» и «Отмена».

Excel VBA Message Box- Yes and No and Cancel

Кнопки MsgBox — повторить попытку и отменить

Вы можете использовать константу vbRetryCancel для отображения кнопок «Повторить» и «Отмена».

Retry and Cancel buttons

Кнопки MsgBox — Кнопка справки

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

help button in the message box dialog box

Обратите внимание, что в этом коде мы объединили две разные константы кнопки (vbRetryCancel + vbMsgBoxHelpButton). Первая часть показывает кнопки «Повторить» и «Отмена», а вторая часть показывает кнопку «Справка».

MsgBox Buttons — Настройка кнопки по умолчанию

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

Ниже приведен код, который установит в качестве кнопки по умолчанию вторую кнопку (кнопка «Нет»).

by default, second button is selected

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

Константы значков Excel VBA MsgBox (примеры)

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

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

Константа значка Описание
vbCritical Показывает значок критического сообщения
vbQuestion Показывает значок вопроса
vbExclamation Показывает значок предупреждения
vbInformation Показывает значок информации

Иконки MsgBox — Критические

Если вы хотите показать критический значок в своем MsgBox, используйте константу vbCritical. Вы можете использовать ее вместе с другими константами кнопки (поставив знак + между кодами).

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

Excel VBA Msgbox - critical icon

Если вы хотите показать критический значок с кнопками Да и Нет, используйте следующий код:

Excel VBA Msgbox - critical icon YesNO

Иконки MsgBox — Вопрос

Если вы хотите показать иконку вопроса в своем MsgBox, используйте константу vbQuestion.

Excel VBA Msgbox - question icon

Иконки MsgBox — Восклицательный знак

Если вы хотите показать восклицательный значок в вашем MsgBox, используйте константу vbExclamation.

Excel VBA Msgbox - exclamation icon

Иконки MsgBox — Информация

Если вы хотите отобразить информационный значок в вашем MsgBox, используйте константу vbInformation.

Excel VBA Msgbox - information

Настройка заголовка и приглашения в MsgBox

При использовании MsgBox вы можете настроить заголовок и сообщения подсказок.

До сих пор в примерах, которые мы видели, использовался Microsoft Excel в качестве заголовка. Если вы не указали аргумент title, MsgBox автоматически использует заголовок приложения (в данном случае это был Microsoft Excel).

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

Excel VBA Msgbox - title

Точно так же вы также можете настроить сообщение подсказки.

Excel VBA Msgbox - prompt

Вы также можете добавить разрывы строк в сообщении подсказки.

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

Excel VBA Msgbox - vbnewline

Вы также можете использовать символ возврата каретки — Chr (13) или перевод строки — Chr (10), чтобы вставить новую строку в сообщение с подсказкой.

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

Присвоение значения MsgBox переменной

До сих пор мы видели примеры, где мы создавали окна сообщений и настраивали кнопки, значки, заголовок и приглашение.

Однако нажатие кнопки ничего не сделало.

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

Поэтому, если я нажимаю кнопку «Да», функция MsgBox возвращает значение (6 или константа vbYes), которое я могу использовать в своем коде. Аналогично, если пользователь выбирает кнопку «Нет», он возвращает другое значение ((7 или константа vbNo)), которое я могу использовать в коде.

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

При нажатии кнопки Константа Значение
Ok vbOk 1
Cancel vbCancel 2
Abort vbAbort 3
Retry vbRetry 4
Ignore vbIgnore 5
Yes vbYes 6
No vbNo 7

Теперь давайте посмотрим, как мы можем контролировать макрос-код VBA в зависимости от того, на какую кнопку нажимает пользователь.

В приведенном ниже коде, если пользователь нажимает кнопку «Да», отображается сообщение «Вы нажали кнопку «Да», а если пользователь нажимает кнопку «Нет», отображается сообщение «Вы нажали кнопку «Нет»».

В приведенном выше коде я присвоил значение функции MsgBox переменной Result. Когда вы нажимаете кнопку «Да», переменная Result получает константу vbYes (или число 6), а когда вы нажимаете «Нет», переменная Result получает константу vbNo (или число 7).

Затем я использовал конструкцию If Then Else, чтобы проверить, содержит ли переменная Result значение vbYes. Если это так, отображается запрос «Вы нажали Да», в противном случае — «Вы нажали Нет».

Вы можете использовать ту же концепцию для запуска кода, если пользователь нажимает Да, и выход из подпрограммы, когда он нажимает Нет.

Примечание. Когда вы присваиваете выход MsgBox переменной, вы должны поместить аргументы функции MsgBox в круглые скобки. Например, в строке Result = MsgBox («Хотите продолжить?», VbYesNo + vbQuestion) вы можете видеть, что аргументы находятся в скобках.

Если вы хотите в дальнейшем углубиться в функцию Message Box, вот официальный документ по ней.

VBA MsgBox

VBA MsgBox is the Pop up Box function to display a message in VBA Language. VBA MsgBox Function helps to display any value to the user with the given prompt. Message Box in VBA is available in all MS Office Application to show the value of a variable or a given string and wait for user to click the buttons. Use the MsgBox to display a Message Box in Excel, Access, Word, PowerPoint (PPT) and Outlook.

Syntax of VBA MsgBox Function

Following is the syntax of the VBA MsgBox Function. Message Box function has one required parameter and four optional parameters.

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

Parameters

MsgBox Function takes the following named arguments. We can pass the values to the MsgBox Function based on our requirement. MsgBox Function will process the given arguments values and shows the pop up box. We can pass the prompt and title as string values, and we can provide the button values from the predefined constants.

  • prompt : Message which you wants to show in the message box body. Prompt is the required parameter,we must pass an argument value to the message box prompt parameter.
  • buttons : We can change the default buttons and style of the message box using the button parameters. VBA MsgBox Function has the predefined list of the constants to set the button styles. This is an optional parameter, the default value of the buttons is vbOKOnly. This will show the message box with simple OK button.
  • title : We can provide the title of the message box window using Title parameter. This is an optional parameter, the default title of the message box is the name of the Application.
  • helpfile : helpfile parameter is useful to set the context-sensitive identifier. This is an optional parameter, context parameter is required when you provide helpfile parameter.
  • context : to prove the context number set to the given help topic. This is an optional parameter, helpfile parameter is required when you provide context parameter.

Button Options

We can pass the button following constant to VBA MsgBox function to can change the default buttons. Here are list of predefined button constants and its values. We can provide the VBA MsgBox constants or respective ENUM value.

Constant Value Description
vbOKOnly 0 This is the default value of the button parameter. You can provide vbOKOnly constant to display OK button only.
vbOKCancel 1 You can provide vbOKCancel constant to display OK and Cancel buttons.
vbAbortRetryIgnore 2 You can provide vbAbortRetryIgnore constant to display Abort, Retry, and Ignore buttons.
vbYesNoCancel 3 You can provide vbYesNoCancel constant to display Yes, No, and Cancel buttons.
vbYesNo 4 You can provide vbYesNo constant to display Yes and No buttons.
vbRetryCancel 5 You can provide vbRetryCancel constant to display Retry and Cancel buttons.

Syntax:

MsgBox prompt:=”Your Prompt”, Buttons:=vbOKCancel

Icon Styles

Following are predefined constants to add an icon to the message box. We can provide the icons constant along with the button constant (0-5) which are listed above.

Constant Value Description
vbCritical 16 vbCritical constants uses to display Critical Message icon.
vbQuestion 32 vbQuestion constants uses to display Warning Message icon.
vbExclamation 48 vbExclamation constants uses to display Warning Message icon.
vbInformation 64 vbInformation constants uses to display Information Message icon.

MsgBox “Your Prompt”, vbInformation + vbOKCancel

Default Buttons

We can also set the default button of the message box. We can mention focused button to be clicked when uses press the enter button.

Constant Value Description
vbDefaultButton1 0 vbDefaultButton1 will set the First button is default.
vbDefaultButton2 256 vbDefaultButton2 will set the Second button is default.
vbDefaultButton3 512 vbDefaultButton3 will set the Third button is default.
vbDefaultButton4 768 vbDefaultButton4 will set the Fourth button is default.

Syntax:

MsgBox “Your Prompt”, vbInformation + vbOKCancel + vbDefaultButton2

Modality, Foreground and Right Alignment

Here are the constants to set the advanced options of the message box. These options helps to determine the modality of the message box and change the alignment of the body text.

Constant Value Description
vbApplicationModal 0 When you set vbApplicationModal option, you must respond to the message box before continuing work in the current application.
vbSystemModal 4096 When you set vbSystemModal option, all of your applications are suspended until you responds to the message box.
vbMsgBoxHelpButton 16384 vbMsgBoxHelpButton uses to add Help button to the message box.
vbMsgBoxSetForeground 65536 We can set the message box window as the foreground window using vbMsgBoxSetForeground.
vbMsgBoxRight 524288 Using vbMsgBoxRight, You can make the text of message box right-aligned.
vbMsgBoxRtlReading 1048576 vbMsgBoxRtlReading helps to set text appearance as right-to-left reading on Hebrew and Arabic system users.

VBA-MsgBox-Modal-Help-and-Right-Alignment

Syntax:

MsgBox “Your Prompt”, vbInformation + vbOKCancel + vbMsgBoxHelpButton + vbMsgBoxRight

Return Values

We can capture the return value of the message box and check using the following constants.

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

VBA-MsgBox-Return-Values

Syntax:

If MsgBox(“Do you wants to continue”, vbInformation + vbYesNo) = vbYes Then
MsgBox “You pressed Yes button”
End If

Examples:

Here are the list of most frequently used examples on VBA MsgBox Function. You can have a look to understand the concepts with suitable examples.

Example to set VBA Buttons:

The following example shows a message box with OK and Cancel buttons.

Example to Change VBA Icon:

Here is a simple example to show a message box with vbInformation Icon and OK and Cancel buttons.

Example to Set VBA Default Button:

The below example sets the second button as default button. We can set any of the four button as default button using the given constants or Enumeration values.

Example to Set VBA Default Button:

The following example will show you the help button in message box. and the text is right-aligned

Example to Return User Selection:

This example will ask the user to press one of the buttons and show the second message based on the return value of the first message box.

VBA MsgBox

The MsgBox function shows a popup with a message, buttons, and an icon. Different arguments can be provided to the Buttons argument to show different buttons and icons. The MsgBox function returns a member of the VbMsgBoxResult enum which indicates which button was pushed by the user.

Syntax:

MsgBox(Prompt,[Buttons As VbMsgBoxStyle=vbOKOnly],[Title],[HelpFile],[Context]) As VbMsgBoxResult

VbMsgBoxStyle

The Buttons parameter of the MsgBox function can be passed constants from the VbMsgBoxStyle enum which determine which type of buttons and icon the message box will have. A button style can be joined with an icon style by adding the constants together.

MsgBox Hello World

Constant Value Description
vbOKOnly 0 OK button only
vbOKCancel 1 OK and Cancel buttons
vbAbortRetryIgnore 2 Abort, Retry, and Ignore buttons
vbYesNoCancel 3 Yes, No, and Cancel buttons
vbYesNo 4 Yes and No buttons
vbRetryCancel 5 Retry and Cancel buttons
vbCritical 16 Critical Message icon (Red «x» circle)
vbQuestion 32 Warning Query icon (Blue «?» circle)
vbExclamation 48 Warning Message icon (Yellow «!» triangle)
vbInformation 64 Information Message icon (Blue «i» circle)
vbDefaultButton1 0 First button is default
vbDefaultButton2 256 Second button is default
vbDefaultButton3 512 Third button is default
vbDefaultButton4 768 Fourth button is default
vbApplicationModal 0 The application is suspended until the message box is dismissed
vbSystemModal 4096 All applications are suspended until the message box is dismissed
vbMsgBoxHelpButton 16384 Help button is added to the message box
vbMsgBoxSetForeground 65536 Sets the message box window as the foreground window
vbMsgBoxRight 524288 Right-aligns text
vbMsgBoxRtlReading 1048576 Specifies right-to-left reading on Hebrew and Arabic systems

VbMsgBoxResult

The MsgBox function returns a value from the VbMsgBoxResult enum which represents the button clicked by the user.

MsgBox Yes No

Constant Value
vbOK 1
vbCancel 2
vbAbort 3
vbRetry 4
vbIgnore 5
vbYes 6
vbNo 7

Copyright © 2021 ‐ 2023 Code Planet LLC. All Rights Reserved.

Excel VBA MsgBox [Message Box] – All You Need to Know!

In Excel VBA, you can use the MsgBox function to display a message box (as shown below):

Default message in a VBA Msgbox

A MsgBox is nothing but a dialog box that you can use to inform your users by showing a custom message or get some basic inputs (such as Yes/No or OK/Cancel).

While the MsgBox dialog box is displayed, your VBA code is halted. You need to click any of the buttons in the MsgBox to run the remaining VBA code.

This Tutorial Covers:

Anatomy of a VBA MsgBox in Excel

A message box has the following parts:

Anatomy of an VBA Msgbox dialog box

  1. Title: This is typically used to display what the message box is about. If you don’t specify anything, it displays the application name – which is Microsoft Excel in this case.
  2. Prompt: This is the message that you want to display. You can use this space to write a couple of lines or even display tables/data here.
  3. Button(s): While OK is the default button, you can customize it to show buttons such as Yes/No, Yes/No/Cancel, Retry/Ignore, etc.
  4. Close Icon: You can close the message box by clicking on the close icon.

Syntax of the VBA MsgBox Function

As I mentioned, MsgBox is a function and has a syntax similar to other VBA functions.

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

  • prompt – This is a required argument. It displays the message that you see in the MsgBox. In our example, the text “This is a sample MsgBox” is the ‘prompt’. You can use up to 1024 characters in the prompt, and can also use it to display the values of variables. In case you want to show a prompt that has multiple lines, you can do that as well (more on this later in this tutorial).
  • [buttons] – It determines what buttons and icons are displayed in the MsgBox. For example, if I use vbOkOnly, it will show only the OK button, and if I use vbOKCancel, it will show both the OK and Cancel buttons. I will cover different kinds of buttons later in this tutorial.
  • [title] – Here you can specify what caption you want in the message dialog box. This is displayed in the title bar of the MsgBox. If you don’t specify anything, it will show the name of the application.
  • [helpfile] – You can specify a help file that can be accessed when a user clicks on the Help button. The help button would appear only when you use the button code for it. If you’re using a help file, you also need to also specify the context argument.
  • [context] – It is a numeric expression that is the Help context number assigned to the appropriate Help topic.

If you’re new to the concept of Msgbox, feel free to ignore the [helpfile] and [context] arguments. I have rarely seen these being used.

Note: All the arguments in square brackets are optional. Only the ‘prompt’ argument is mandatory.

Excel VBA MsgBox Button Constants (Examples)

In this section, I will cover the different types of buttons that you can use with a VBA MsgBox.

Before I show you the VBA code for it and how the MsgBox looks, here is a table that lists all the different button constants you can use.

Button Constant Description
vbOKOnly Shows only the OK button
vbOKCancel Shows the OK and Cancel buttons
vbAbortRetryIgnore Shows the Abort, Retry, and Ignore buttons
vbYesNo Shows the Yes and No buttons
vbYesNoCancel Shows the Yes, No, and Cancel buttons
vbRetryCancel Shows the Retry and Cancel buttons
vbMsgBoxHelpButton Shows the Help button. For this to work, you need to use the help and context arguments in the MsgBox function
vbDefaultButton1 Makes the first button default. You can change the number to change the default button. For example, vbDefaultButton2 makes the second button as the default

Note: While going through the examples of creating different buttons, you may wonder what’s the point of having these buttons if it doesn’t have any impact on the code.

It does! Based on the selection, you can code what you want the code to do. For example, if you select OK, the code should continue, and if you click Cancel, the code should stop. This can be done by using variables and assigning the value of the Message Box to a variable. We will cover this in the later sections of this tutorial.

Now let’s have a look at some examples of how the different buttons can be displayed in a MsgBox and how it looks.

MsgBox Buttons – vbOKOnly (Default)

If you only use the prompt and don’t specify any of the arguments, you will get the default message box as shown below:

Sample message box

Below is the code that will give this message box:

Note that the text string needs to be in double quotes.

You can also use the button constant vbOKOnly, but even if you don’t specify anything, it’s taken as default.

MsgBox Buttons – OK & Cancel

If you only want to show the OK and the Cancel button, you need to use the vbOKCancel constant.

ok and cancel buttons in a message box

MsgBox Buttons – Abort, Retry, and Ignore

You can use the ‘vbAbortRetryIgnore’ constant to show the Abort, Retry, and the Ignore buttons.

Excel VBA Msgbox - Abort Retry and Cancel buttons

MsgBox Buttons – Yes and No

You can use the ‘vbYesNo’ constant to show the Yes and No buttons.

Yes and No buttons in a message box

MsgBox Buttons – Yes, No and Cancel

You can use the ‘vbYesNoCancel’ constant to show the Yes, No, and Cancel buttons.

Excel VBA Message Box- Yes and No and Cancel

MsgBox Buttons – Retry and Cancel

You can use the ‘vbRetryCancel’ constant to show the Retry and Cancel buttons.

Retry and Cancel buttons

MsgBox Buttons – Help Button

You can use the ‘vbMsgBoxHelpButton’ constant to show the help button. You can use it with other button constants.

Note that in this code, we have combined two different button constants (vbRetryCancel + vbMsgBoxHelpButton). The first part shows the Retry and Cancel buttons and the second part shows the Help button.

MsgBox Buttons – Setting a Default Button

You can use the ‘vbDefaultButton1’ constant to set the first button as default. This means that the button is already selected and if you press enter, it executes that button.

Below is the code that will set the second button (the ‘No’ button) as the default.

In most cases, the left-most button is the default button. You can choose other buttons using vbDefaultButton2, vbDefaultButton3, and vbDefaultButton4.

Excel VBA MsgBox Icon Constants (Examples)

Apart from the buttons, you can also customize the icons that are displayed in the MsgBox dialog box. For example, you can have a red critical icon or a blue information icon.

Below is a table that lists the code that will show the corresponding icon.

Icon Constant Description
vbCritical Shows the critical message icon
vbQuestion Shows the question icon
vbExclamation Shows the warning message icon
vbInformation Shows the information icon

MsgBox Icons – Critical

If you want to show a critical icon in your MsgBox, use the vbCritical constant. You can use this along with other button constants (by putting a + sign in between the codes).

For example, below is a code that will show the default OK button with a critical icon.

If you want to show the critical icon with Yes and No buttons, use the following code:

MsgBox Icons – Question

If you want to show a critical icon in your MsgBox, use the vbQuestion constant.

MsgBox Icons – Exclamation

If you want to show an exclamation icon in your MsgBox, use the vbExclamation constant.

MsgBox Icons – Information

If you want to show an information icon in your MsgBox, use the vbInformation constant.

Excel VBA Msgbox - information

Customizing Title and Prompt in the MsgBox

When using MsgBox, you can customize the title and the prompt messages.

So far, the example we have seen have used Microsoft Excel as the title. In case you don’t specify the title argument, MsgBox automatically uses the title of the application (which has been Microsoft Excel in this case).

You can customize the title by specifying it in the code as shown below:

Excel VBA Msgbox - title

Similarly, you can also customize the prompt message.

Excel VBA Msgbox - prompt

You can also add line breaks in the prompt message.

In the below code, I have added a line break using ‘vbNewLine’.

Excel VBA Msgbox - vbnewline

You can also use the carriage return character – Chr(13) – or line feed – Chr(10) to insert a new line in the prompt message.

Note that you can add a new line to the prompt message only and not the title.

Assigning MsgBox Value to a Variable

So far, we have seen the examples where we have created message boxes and customized the buttons, icons, title, and prompt.

However, clicking a button has done nothing.

With MsgBox function in Excel, you can decide what you want to do when a user clicks a specific button. And this is possible as every button has a value associated to it.

So if I click on the Yes button, the MsgBox function returns a value (6 or the constant vbYes) which I can use in my code. Similarly, is the user selects the No button, it returns a different value ((7 or the constant vbNo)) that I can use in the code.

Below is a table that shows the exact values and the constant returned by the MsgBox function. You don’t need to memorize these, just be aware of it and you can use the constants which are easier to use.

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

Now let’s see how we can control the VBA macro code based on what button a user clicks.

In the below code, if the user clicks Yes, it displays the message “You Clicked Yes”, and if the user clicks No, it displays, “You clicked No”.

In the above code, I have assigned the value of the MsgBox function to the Result variable. When you click Yes button, the Result variable gets the vbYes constant (or the number 6) and when you click No, the Result variable gets the vbNo constant (or the number 7).

Then I used an If Then Else construct to check if the Result variable holds the value vbYes. If it does, it shows the prompt “You Clicked Yes”, else it shows “You clicked No”.

You can use the same concept to run a code if a user clicks Yes and exit the sub when he/she clicks No.

If you want to further dig into the Message Box function, here is the official document on it.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *