Msgbox yesno vba excel

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

Использование функции 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».

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

На чтение 10 мин. Просмотров 38.4k.

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

Default message in a VBA Msgbox

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

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

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

Содержание

  1. Анатомия VBA MsgBox в Excel
  2. Синтаксис функции VBA MsgBox
  3. Константы кнопки Excel VBA MsgBox (примеры)
  4. Константы значков Excel VBA MsgBox (примеры)
  5. Настройка заголовка и приглашения в MsgBox
  6. Присвоение значения MsgBox переменной

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

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

Anatomy of an VBA Msgbox dialog box

  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

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

Sub DefaultMsgBox()
MsgBox "This is a sample box"
End Sub

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

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

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

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

Sub MsgBoxOKCancel()
MsgBox "Want to Continue?", vbOKCancel
End Sub

ok and cancel buttons in a message box

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

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

Sub MsgBoxAbortRetryIgnore()
MsgBox "What do you want to do?", vbAbortRetryIgnore
End Sub

Excel VBA Msgbox - Abort Retry and Cancel buttons

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

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

Sub MsgBoxYesNo()
MsgBox "Should we stop?", vbYesNo
End Sub

Yes and No buttons in a message box

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

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

Sub MsgBoxYesNoCancel()
MsgBox "Should we stop?", vbYesNoCancel
End Sub

Excel VBA Message Box- Yes and No and Cancel

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

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

Sub MsgBoxRetryCancel()
MsgBox "What do you want to do next?", vbRetryCancel
End Sub

Retry and Cancel buttons

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

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

Sub MsgBoxRetryHelp()
MsgBox "What do you want to do next?", vbRetryCancel + vbMsgBoxHelpButton
End Sub

help button in the message box dialog box

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

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

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

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

Sub MsgBoxOKCancel()
MsgBox "What do you want to do next?", vbYesNoCancel + vbDefaultButton2
End Sub

by default, second button is selected

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

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

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

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

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

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

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

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

Sub MsgBoxCriticalIcon()
MsgBox "This is a sample box", vbCritical
End Sub

Excel VBA Msgbox - critical icon

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

Sub MsgBoxCriticalIcon()
MsgBox "This is a sample box", vbYesNo + vbCritical
End Sub

Excel VBA Msgbox - critical icon YesNO

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

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

Sub MsgBoxQuestionIcon()
MsgBox "This is a sample box", vbYesNo + vbQuestion
End Sub

Excel VBA Msgbox - question icon

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

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

Sub MsgBoxExclamationIcon()
MsgBox "This is a sample box", vbYesNo + vbExclamation
End Sub

Excel VBA Msgbox - exclamation icon

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

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

Sub MsgBoxInformationIcon()
MsgBox "This is a sample box", vbYesNo + vbInformation
End Sub

Excel VBA Msgbox - information

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

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

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

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

Sub MsgBoxInformationIcon()
MsgBox "Do you want to continue?", vbYesNo + vbQuestion, "Step 1 of 3"
End Sub

Excel VBA Msgbox - title

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

Excel VBA Msgbox - prompt

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

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

Sub MsgBoxInformationIcon()
MsgBox "Do you want to continue?" & vbNewLine & "Click Yes to Continue", vbYesNo + vbQuestion, "Step 1 of 3"
End Sub

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 в зависимости от того, на какую кнопку нажимает пользователь.

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

Sub MsgBoxInformationIcon()
Result = MsgBox("Do you want to continue?", vbYesNo + vbQuestion)
If Result = vbYes Then
MsgBox "You clicked Yes"
Else: MsgBox "You clicked No"
End If
End Sub

Yes No prompt based on user selection

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

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

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

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

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

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.

Note: In this tutorial, I will be using the words message box and MsgBox interchangeably. When working with Excel VBA, you always need to use MsgBox.

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:

Sub DefaultMsgBox()
MsgBox "This is a sample box"
End Sub

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.

Sub MsgBoxOKCancel()
MsgBox "Want to Continue?", vbOKCancel
End Sub

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.

Sub MsgBoxAbortRetryIgnore()
MsgBox "What do you want to do?", vbAbortRetryIgnore
End Sub

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.

Sub MsgBoxYesNo()
MsgBox "Should we stop?", vbYesNo
End Sub

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.

Sub MsgBoxYesNoCancel()
MsgBox "Should we stop?", vbYesNoCancel
End Sub

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.

Sub MsgBoxRetryCancel()
MsgBox "What do you want to do next?", vbRetryCancel
End Sub

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.

Sub MsgBoxRetryHelp()
MsgBox "What do you want to do next?", vbRetryCancel + vbMsgBoxHelpButton
End Sub

help button in the message box dialog box

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.

Sub MsgBoxOKCancel()
MsgBox "What do you want to do next?", vbYesNoCancel + vbDefaultButton2
End Sub

by default, second button is selected

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.

Sub MsgBoxCriticalIcon()
MsgBox "This is a sample box", vbCritical
End Sub

Excel VBA Msgbox - critical icon

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

Sub MsgBoxCriticalIcon()
MsgBox "This is a sample box", vbYesNo + vbCritical
End Sub

Excel VBA Msgbox - critical icon YesNO

MsgBox Icons – Question

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

Sub MsgBoxQuestionIcon()
MsgBox "This is a sample box", vbYesNo + vbQuestion
End Sub

Excel VBA Msgbox - question icon

MsgBox Icons – Exclamation

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

Sub MsgBoxExclamationIcon()
MsgBox "This is a sample box", vbYesNo + vbExclamation
End Sub

Excel VBA Msgbox - exclamation icon

MsgBox Icons – Information

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

Sub MsgBoxInformationIcon()
MsgBox "This is a sample box", vbYesNo + vbInformation
End Sub

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:

Sub MsgBoxInformationIcon()
MsgBox "Do you want to continue?", vbYesNo + vbQuestion, "Step 1 of 3"
End Sub

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’.

Sub MsgBoxInformationIcon()
MsgBox "Do you want to continue?" & vbNewLine & "Click Yes to Continue", vbYesNo + vbQuestion, "Step 1 of 3"
End Sub

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”.

Sub MsgBoxInformationIcon()
Result = MsgBox("Do you want to continue?", vbYesNo + vbQuestion)
If Result = vbYes Then
MsgBox "You clicked Yes"
Else: MsgBox "You clicked No"
End If
End Sub

Yes No prompt based on user selection

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.

Note: When you assign the MsgBox output to a variable, you need to put the arguments of MsgBox function in parenthesis. For example, in the line Result = MsgBox(“Do you want to continue?”, vbYesNo + vbQuestion), you can see that the arguments are within parenthesis.

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

You May Also Like the Following Excel VBA Tutorials:

  • Excel VBA Split Function.
  • Excel VBA InStr Function.
  • Working with Cells and Ranges in Excel VBA.
  • Working with Worksheets in VBA.
  • Working with Workbooks in VBA.
  • Using Loops in Excel VBA.
  • Understanding Excel VBA Data Types (Variables and Constants)
  • How to Create and Use Personal Macro Workbook in Excel.
  • Useful Excel Macro Code Examples.
  • Using For Next Loop in Excel VBA.
  • Excel VBA Events – An Easy (and Complete) Guide.
  • How to Run a Macro in Excel – A Complete Step-by-Step Guide.
  • How to Create and Use an Excel Add-in.
  • Using Active Cell in VBA in Excel (Examples)

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 in excel vba vbyesno
  • Ms word это текстовый редактор или нет
  • Ms word это текстовый процессор электронная таблица
  • Ms word это текстовый процессор или нет