Excel макрос вывести сообщение

Ранее мы уже узнали, в чем разница между макросами и процедурами, кроме того, попробовали самостоятельно записать простенький макрос. Теперь попробуем написать текст процедуры, позволяющей вывести текстовое сообщение. Для этого откроем приложение Word либо Excel, создадим новый документ или рабочую книгу и нажмем сочетание клавиш Alt+F11 для активизации редактора Visual Basic. Далее в окне Project Explorer выделим проект с именем созданного документа/рабочей книги и добавим в него новый модуль через меню Insert/Module. Редактор VB добавляет в проект новый модуль и открывает для него Code Window – окно, в котором пишется программный код процедуры. Исходный код новой процедуры VBA можно ввести в любом месте модуля (номера строк писать не нужно). Напишем классическую программу, выводящую диалоговое окно с сообщением «Hello, World!». Состоять она будет из трех строк.

Sub HelloWorld()
     MsgBox “Hello, World!”
End Sub

Первая строка любой процедуры должна начинаться с ключевого слова Sub (сокращение от Subprogramm), за которым через пробел следует имя процедуры и далее пара пустых, круглых скобок, наличие которых обязательно.

Вторая строка процедуры HelloWorld образует тело процедуры и состоит из единственного оператора, выполняющего полезную работу. Тело процедуры может состоять как из одного, так и из многих операторов, а может и не состоять ни из одного оператора. Оператор MsgBox выводит диалоговое окно с текстовым сообщением «Hello, World!» для пользователя процедуры.

Третья и последняя строка вышеприведенного листинга завершает процедуру и состоит всего из двух слов – End Sub, чем отмечает конец программы. При выполнении этой инструкции никаких видимых действий не происходит, но при этом высвобождается память, временно использованная при выполнении процедуры.

Различные сообщения либо любая другая информация, которую процедура выводит на экран, отправляет на принтер либо записывает в файл, называется выходом. Оператор MSgBox – это простейшая форма экранного выхода, используемая в процедурах VBA.

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

Sub HelloWorld()
     MsgBox "Hello, World!", vbInformation, "Окно приветствия"
End Sub

Остается выполнить написанный исходный код и посмотреть что получилось. Переключаемся в окно приложения (Word, Excel), нажимаем сочетание клавиш Alt+F8, выбираем в открывшемся окне из предложенного списка строку с именем процедуры «HelloWorld» и нажимаем кнопку «Выполнить».

Другие материалы по теме:

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

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

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)

Create a pop-up message box in Excel using VBA Macros. This allows you to show a message to the user and to get input back, depending on which buttons were clicked in the pop-up message.

To output a message in Excel, we use the MsgBox function. Below, you will find many examples that should suit your needs.

Sections:

Syntax

Example 1 — Output Basic Text

Example 2 — Add Buttons to the Message Box

Example 3 — Figure Out Which Button Was Clicked

Example 4 — Do Something After the User Clicks a Button

Example 5 — Change MsgBox Appearance

Notes

Syntax

MsgBox(prompt, [buttons], [title], [helpfile], [context])
Argument Description
Prompt

The text that will be in the message box. This is the only required argument for the MsgBox function.

[Buttons]

Allows you to display different buttons and icons in the message box.

[Title]

Text that appears in the title bar of the message box.

[Helpfile]

Not needed. Allows for a specific help file to be used.

[Context]

Not needed. Required if the helpfile argument is used.

[] means it is an optional argument.

Button Arguments

These are the values that can be entered for the buttons argument. You will use the VB Codes to add them to the message box. Examples below will include some of these options so you can better understand them.

VB Code Description Value

vbOKOnly

OK Button. Default.

0

vbOKCancel

OK and Cancel buttons.

1

vbAbortRetryIgnore

Abort, Retry, and Ignore buttons.

2

vbYesNoCancel

Yes, No, and Cancel buttons.

3

vbYesNo

Yes and No buttons.

4

vbRetryCancel

Retry and Cancel buttons.

5

vbCritical

Displays the Critical Message icon in the message box window.

16

vbQuestion

Displays the Warning Query icon in the message box window.

32

vbExclamation

Displays the Warning Message icon in the message box window.

48

vbInformation

Displays the Information Message icon in the message box window.

64

vbDefaultButton1

Selects the first button in the message box by default.

0

vbDefaultButton2

Selects the second button in the message box by default.

256

vbDefaultButton3

Selects the third button in the message box by default.

512

vbDefaultButton4

Selects the fourth button in the message box by default.

768

vbApplicationModal

Application modal; the user must respond to the message box before continuing work in Excel.

0

vbSystemModal

System modal; all applications are suspended until the user responds to the message box.

4096

VbMsgBoxSetForeground

Specifies the message box window as the foreground window

65536

vbMsgBoxRight

Text is right aligned

524288

Values Returned from Button Clicks in the Message Box

When a user clicks one of the buttons that are in the message box, a value will be returned to VBA; that value corresponds to the button that was clicked and is listed below.

Button Clicked Returned Constant Returned # Value

OK

vbOK

1

Cancel

vbCancel

2

Abort

vbAbort

3

Retry

vbRetry

4

Ignore

vbIgnore

5

Yes

vbYes

6

No

vbNo

7

Example 1 — Output Basic Text

Basic message box with text.

This is the simplest form of outputting a message.

MsgBox "Hi, this is my message."

a63ffa7cd8882f6ceadecdb8df1f21ba.jpg

Running the macro we get this:

c46b3081178c9e6626f8785ee388b478.jpg

Remember, the OK button is there by default and clicking that simply closes the pop-up message box window.

Example 2 — Add Buttons to the Message Box

Message box with multiple buttons.

MsgBox "Hi, this is my message.", vbYesNoCancel

db0f8fdeac20a772711bf8eafc93ce33.jpg

I added a comma after the display text and then input one of the VB codes from the Button Arguments list above.

2dea7d7b5e6391765e3a6b6661789ebd.jpg

Run the macro and we get this in Excel:

f8ac44abed8da3166c9ce60897767240.jpg

Example 3 — Figure Out Which Button Was Clicked

When a button is clicked, it sends a value back to Excel. Now, we need to capture that value so we can do something with it.

response = MsgBox("Hi, this is my message.", vbYesNoCancel)

4201571bd7a681c0b0102d55a8ff2ec2.jpg

All we have to do is to set a variable equal to the output of the MsgBox function. Here, the variable response is equal to the output of the function, which means that we type response =  and then the msgbox function.

Note also that there are now parentheses surrounding the arguments for the MsgBox function; these weren’t included before because they weren’t needed. Often, they aren’t used when creating simple pop-up windows.

I will now output the variable response into a Msgbox of its own so you can see the value it returns after a button was clicked.

Here is the final code for this example:

b6056271ee5283726f0493532c267437.jpg

Run it and you get this:

7ee7a2cc2dd7f2214b8abc8f2e9773a9.jpg

Click one of the buttons and the next message box will open with the value that was returned as a result of the button click in the first window.

ad4d29f171f3b99745743da22c860edb.jpg

A 6 is returned, which means the button Yes was clicked. We know this from the table above «Values Returned from Button Clicks in the Message Box», which lists the values that each button click will return.

Example 4 — Do Something After the User Clicks a Button

Now that you know how to determine which button was clicked, let’s do something useful with it.

I will make a simple IF statement that checks which button was clicked and outputs a message based on that.

Sub button_action_msgbox()

response = MsgBox("Hi, this is my message.", vbYesNo)

If response = 6 Then
    MsgBox "You clicked Yes"
ElseIf response = 7 Then
    MsgBox "You clicked No"
End If

End Sub

74e8e0e525ee2b884813984e0bb0585f.jpg

Run the macro:

5a3ec2e9d11e8f438483a7b79788801a.jpg

Hit one of the buttons and the next part of the macro will run and the corresponding msgbox will appear:

1a40178ea6aa380be3256decf2a543f8.jpg

At this point, we have created a useful pop-up message box that solicits feedback and does something with that feedback.

Example 5 — Change MsgBox Appearance

You can add some additional things to the pop-up window to change its look and feel and here I will include some of those options, including a custom title for the window.

Sub button_style_msgbox()

MsgBox _
    "Hi, this is my message.", _
    vbOKOnly + vbInformation, _
    "Custom Title"

End Sub

8d756ee11ae6c7f7f5dbd0ba45030a52.jpg

First, notice that I used «_» at the end of each line so that I could place this piece of code on multiple lines.

Second, notice that there is now a custom title called Custom Title that will appear for the msgbox.

Third, notice that there is more than one option for the buttons argument and that each argument is separated with a plus sign (+) like this: vbOKOnly + vbInformation.

Run the macro and we get this:

12471f5ba0f2c25a758a04457f3b1079.jpg

The option vbOKOnly meant there would be only an OK button. The option vbInformation put that image with the i inside the blue circle in there. The custom title appears in the upper-left corner of the pop-up message box window.

Notes

These are a few examples that should get you comfortable using the Message Box pop-up window feature in macros in Excel.

This is a great way to give some information to your user that they must process or at least must reply to in some way before continuing.

Make sure to download the sample file attached to this tutorial to get all of the sample VBA Macro codes.

Excel VBA Tutorial about how to create a message box with macrosIn this VBA Tutorial, you learn how to create message boxes and specify their most important characteristics, such as the following:

  1. How to specify the message displayed in the message box.
  2. How to customize or specify the buttons displayed by the message box.
  3. How to work with the value returned by the MsgBox function, and assign this value to a variable.
  4. How to specify the icon style used by the message box.
  5. How to specify the default button of in the message box.
  6. How to specify the modality of the message box.

This Excel VBA MsgBox Tutorial is accompanied by an Excel workbook containing the macros I use in the examples below. You can get immediate access to this example workbook by clicking the button below.

Get immediate free access to the Excel VBA MsgBox Tutorial workbook example

Use the following Table of Contents to navigate to the section that interests you.

Related VBA and Macro Tutorials

The following VBA and Macro Tutorials may help you better understand and implement the contents below:

  • General VBA constructs and structures:
    • Learn how to start working with macros here.
    • Learn about essential VBA terms here.
    • Learn how to enable or disable macros here.
    • Learn how to work with the VBE here.
    • Learn how to create and work with Sub procedures here.
    • Learn how to declare and work with variables here.
    • Learn about VBA data types here.
    • Learn how to work with functions in VBA here.
  • Practical VBA applications and macro examples:
    • Learn how to create UserForms here.

You can find additional VBA and Macro Tutorials in the Archives.

#1: Create MsgBox

VBA code to create MsgBox

To create a basic message box with VBA, use a statement with the following structure:

MsgBox Prompt:=PromptString

Process to create MsgBox

To create a basic message box with VBA, use the MsgBox function (MsgBox …).

VBA statement explanation

  1. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a basic message box using this statement structure:

      • The displayed message is PromptString.
      • The message box contains a single button: OK. For purposes of including other custom button layouts, please refer to the appropriate sections of this Tutorial.
      • The value returned by the MsgBox function is vbOK (or 1). For purposes of assigning the value returned by the MsgBox function to a variable, please refer to the appropriate section of this Tutorial.
  2. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • The maximum length of PromptString is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters within PromptString.
      • PromptString can be composed of multiple lines. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.

Macro example to create MsgBox

The following macro example creates a basic message box with the message “Create Excel VBA MsgBox”.

Sub createMsgBox()
    'source: https://powerspreadsheets.com/
    'creates a message box
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'create a message box
    MsgBox Prompt:="Create Excel VBA MsgBox"

End Sub

Effects of executing macro example to create MsgBox

The following image illustrates the results of executing the macro example.

Macro creates MsgBox

#2: Create MsgBox with multiple lines (new line or line break)

VBA code to create MsgBox with multiple lines (new line or line break)

To create a message box with multiple lines (by including a new line or using line breaks) using VBA, use a statement with the following structure:

MsgBox Prompt:=PromptString1 & NewLineCharacter & PromptString2 & ... & NewLineCharacter & PromptString#

Process to create MsgBox with multiple lines (new line or line break)

To create a message box with multiple lines (by including a new line or using line breaks) using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox …).
  2. Specify the message displayed in the message box as an appropriately concatenated (with the & character) combination of:
    • Strings (PromptString1, PromptString2, …, PromptString#); and
    • Characters that create a new line or line break (NewLineCharacter).

VBA statement explanation

  1. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with multiple lines (by including a new line or using line breaks) using this statement structure:

      • The displayed message is that specified by the Prompt argument.
      • The message box contains a single button: OK. For purposes of including other custom button layouts, please refer to the appropriate sections of this Tutorial.
      • The value returned by the MsgBox function is vbOK (or 1). For purposes of assigning the value returned by the MsgBox function to a variable, please refer to the appropriate section of this Tutorial.
  2. Item: Prompt:=PromptString1 & NewLineCharacter & PromptString2 & … & NewLineCharacter & PromptString#.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box.

      When you create a message box with multiple lines (by including a new line or using line breaks), you build the string expression assigned to Prompt (PromptString1 & NewLineCharacter & PromptString2 & … & NewLineCharacter & PromptString#) by concatenating as many strings (PromptString1, PromptString2, …, PromptString#) and newline characters (NewLineCharacter) as required.

      The maximum length of the string expression assigned to prompt is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters you include.

      If you explicitly declare a variable to represent this string expression, you can usually work with the String data type.

  3. Item: PromptString1, PromptString2, …, PromptString#.
    • VBA construct: Strings expressions.
    • Description: PromptStrings are the strings (excluding the new line characters) that determine the message displayed in the message box.

      If you explicitly declare variables to represent the different PromptStrings, you can usually work with the String data type.

  4. Item: &.
    • VBA construct: Concatenation (&) operator.
    • Description: The & operator carries out string concatenation. Therefore, & concatenates the different strings (PromptString1, PromptString2, …, PromptString#) and new line characters (NewLineCharacter) you use to specify the string expression assigned to the Prompt argument.
  5. Item: NewLineCharacter.
    • VBA construct: A character or character combination returning 1 of the following:
      • Carriage return.
      • Linefeed.
      • Carriage return linefeed combination.
      • New line (which is platform specific).
    • Description: Specify NewLineCharacter using any of the constants or character codes (with the Chr function) listed below.
      Constant Equivalent Chr function General Description
      vbLf Chr(10) Linefeed
      vbCr Chr(13) Carriage return
      vbCrLf Chr(13) & Chr(10) Carriage return linefeed combination
      vbNewLine Chr(13) & Chr(10) in Excel for Windows or Chr(13) in Excel for Mac New line character, which is platform specific

Macro example to create MsgBox with multiple lines (new line or line break)

The following macro example creates a message box with a message displayed in multiple lines by adding a new line as follows:

  • Line #1: “Create Excel VBA MsgBox”.
  • Line #2: “And add a new line”.
Sub MsgBoxNewLine()
    'source: https://powerspreadsheets.com/
    'creates a message box with a new line or line break
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'create a message box with a new line or line break
    MsgBox Prompt:="Create Excel VBA MsgBox" & vbNewLine & "And add a new line"

End Sub

Effects of executing macro example to create MsgBox with multiple lines (new line or line break)

The following image illustrates the results of executing the macro example. Notice that, as expected, the message box contains multiple lines.

Macro creates MsgBox with multiple lines

#3: Create MsgBox with title

VBA code to create MsgBox with title

To create a message box with title using VBA, use a statement with the following structure:

MsgBox Prompt:=PromptString, Title:=TitleString

Process to create MsgBox with title

To create a message box with title using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox …).
  2. Specify the message displayed in the message box (Prompt:=PromptString).
  3. Specify the message box title (Title:=TitleString).

VBA statement explanation

  1. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with title using this statement structure:

      • The displayed message is PromptString.
      • The message box contains a single button: OK. For purposes of including other custom button layouts, please refer to the appropriate sections of this Tutorial.
      • The value returned by the MsgBox function is vbOK (or 1). For purposes of assigning the value returned by the MsgBox function to a variable, please refer to the appropriate section of this Tutorial.
  2. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • The maximum length of PromptString is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters within PromptString.
      • PromptString can be composed of multiple lines. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  3. Item: Title:=TitleString.
    • VBA construct: Title argument of the MsgBox function and string expression.
    • Description: Use the Title argument of the MsgBox function to specify the title displayed in the title bar of the message box. If you omit the Title argument, the title displayed in the title bar of the message box is “Microsoft Excel”.

      You generally specify TitleString as a string expression. If you explicitly declare a variable to represent TitleString, you can usually work with the String data type.

Macro example to create MsgBox with title

The following macro example creates a message box with:

  • The message “Create Excel VBA MsgBox”; and
  • The title “Add title to MsgBox.
Sub MsgBoxTitle()
    'source: https://powerspreadsheets.com/
    'creates a message box with a title
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'create a message box with a title
    MsgBox Prompt:="Create Excel VBA MsgBox", Title:="Add title to MsgBox"

End Sub

Effects of executing macro example to create MsgBox with title

The following image illustrates the results of executing the macro example. Notice that, as expected, the message box contains a custom title (Add title to MsgBox).

Macro creates MsgBox with title

#4: Create MsgBox that returns value based on user input and assigns value to a variable

VBA code to create MsgBox that returns value based on user input and assigns value to a variable

To create a message box that:

  • Returns a value based on the user’s input; and
  • Assigns that value to a variable;

with VBA, use a statement with the following structure:

Variable = MsgBox(Prompt:=PromptString, Buttons:=ButtonsExpression)

Process to create MsgBox that returns value based on user input and assigns value to a variable

To create a message box that:

  • Returns a value based on the user’s input; and
  • Assigns that value to a variable;

with VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox(…)).
  2. Specify the buttons to be displayed in the message box (Buttons:=ButtonsExpression).
  3. Assign the value returned by the MsgBox function to a variable (Variable = MsgBox(…)).

VBA statement explanation

  1. Item: Variable.
    • VBA construct: Variable.
    • Description: Variable you want to hold the value returned by the MsgBox function.

      If you explicitly declare Variable, you can usually work with the Integer data type.

  2. Item: =.
    • VBA construct: Assignment (=) operator.
    • Description: The = operator assigns the Integer value returned by the MsgBox function to Variable.
  3. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box that returns a value based on user input (and assigns the value to a variable) using this statement structure:

      • The displayed message is PromptString.
      • The message box contains the buttons specified by ButtonsExpression. For purposes of working with the main custom button layouts, please refer to the appropriate sections of this Tutorial.
  4. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • The maximum length of PromptString is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters within PromptString.
      • PromptString can be composed of multiple lines. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  5. Item: Buttons:=ButtonsExpression.
    • VBA construct: Buttons argument of the MsgBox function.
    • Description: Use the Buttons argument of the MsgBox function to specify the following:
      • Number and type of buttons displayed in the message box.
      • Icon style for the message box.
      • Default button in the message box.
      • Modality of the message box.

      For these purposes, you can generally specify ButtonsExpression as a sum of the following 4 groups of values or built-in constants:

      • Values or built-in constants that specify the number and type of buttons displayed in the message box, as follows:
        Built-in constant Value Description
        vbOKOnly 0 Message box with only OK button
        vbOKCancel 1 Message box with OK and Cancel buttons
        vbAbortRetryIgnore 2 Message box with Abort, Retry and Ignore buttons
        vbYesNoCancel 3 Message box with Yes, No and Cancel buttons
        vbYesNo 4 Message box with Yes and No buttons
        vbRetryCancel 5 Message box with Retry and Cancel buttons

        For purposes of working with these different custom button layouts, please refer to the appropriate sections of this Tutorial.

      • Values or built-in constants that specify the icon style of the message box, as follows:
        Built-in constant Value Description
        vbCritical 16 Message box with Critical Message icon
        vbQuestion 32 Message box with Warning Query icon
        vbExclamation 48 Message box with Warning Message icon
        vbInformation 64 Message box with Information Message icon

        For purposes of working with these different icon styles, please refer to the appropriate sections of this Tutorial.

      • Values or built-in constants that specify the default button in the message box, as follows:
        Built-in constant Value Description
        vbDefaultButton1 0 Message box where first button is default button
        vbDefaultButton2 256 Message box where second button is default button
        vbDefaultButton3 512 Message box where third button is default button
        vbDefaultButton4 768 Message box where fourth button is default button

        For purposes of working with these different custom default button options, please refer to the appropriate sections of this Tutorial.

      • Values or built-in constants that specify the modality of the message box, as follows:
        Built-in constant Value Description
        vbApplicationModal 0 Application modal message box
        vbSystemModal 4096 System modal message box

        For purposes of working with this different modality options, please refer to the appropriate sections of this Tutorial.

      When specifying ButtonsExpression:

      • Specify ButtonsExpression as a sum of the applicable values or built-in constants.
      • Omit the values from the groups you don’t specify.
      • Use a maximum of 1 value from each of these 4 groups.
      • In addition to the values and built-in constants I list above, the Buttons argument accepts the following 4 settings:
        Built-in constant Value Description
        vbMsgBoxHelpButton 16384 Message box with an additional Help button.

        The MsgBox function also accepts a (optional) helpfile and context arguments that specify the applicable Help file and Help context number.

        Clicking on the Help button results in the applicable help being provided. The MsgBox function only returns a value when the user clicks 1 of the other buttons in the message box.

        vbMsgBoxSetForeground 65536 Message box is the foreground window
        vbMsgBoxRight 524288 Text within the message box is aligned to the right
        vbMsgBoxRtlReading 1048576 Text within the message box is displayed as right-to-left reading on Hebrew and Arabic systems

      The default value of the Buttons argument is 0. Therefore, if you omit specifying the Buttons argument, the result is an Application modal message box with a single button (OK), which is also the default button, and no special icon style.

Macro example to create MsgBox that returns value based on user input and assigns value to a variable

The following macro example does the following:

  1. Creates a message box that returns a value based on the user’s input.
  2. Assigns this value to a variable (myVariable = MsgBox(…)).
  3. Creates a second message box that displays the value held by variable.

The message box has the following characteristics:

  • Displays the message “Create Excel VBA MsgBox”.
  • Has 2 buttons: Yes and No (vbYesNo). The second button (vbDefaultButton2) is the default.
  • Displays an Information Message icon (vbInformation).
  • Is System modal (vbSystemModal).
Sub MsgBoxVariable()
    'source: https://powerspreadsheets.com/
    '(1) creates a message box that returns a value, and (2) assigns value to a variable
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'declare variable to hold value returned by message box
    Dim myVariable As Integer

    '(1) create a message box that returns a value, and (2) assign this value to a variable
    myVariable = MsgBox(Prompt:="Create Excel VBA MsgBox", Buttons:=vbYesNo + vbInformation + vbDefaultButton2 + vbSystemModal)

    'display message box with value held by variable
    MsgBox myVariable

End Sub

Effects of executing macro example to create MsgBox that returns value based on user input and assigns value to a variable

The following image illustrates the results of executing the macro example. Notice that, as expected, the macro displays a second message box with the value returned by the MsgBox function and held by the variable.

Macro creates MsgBox that returns value

#5: Create MsgBox with OK button

VBA code to create MsgBox with OK button

To create a message box with an OK button using VBA, use a statement with the following structure:

MsgBox Prompt:=PromptString, Buttons:=vbOKOnly

Process to create MsgBox with OK button

To create a message box with an OK button using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox …).
  2. Specify that the message box should display a single(OK) button (Buttons:=vbOKOnly).

VBA statement explanation

  1. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with OK button using this statement structure:

      • The displayed message is PromptString.
      • The message box contains a single button: OK.
      • The value returned by the MsgBox function is vbOK (or 1). For purposes of assigning the value returned by the MsgBox function to a variable, please refer to the appropriate section of this Tutorial.
  2. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • The maximum length of PromptString is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters within PromptString.
      • PromptString can be composed of multiple lines. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  3. Item: Buttons:=vbOKOnly.
    • VBA construct: Buttons argument of the MsgBox function and vbOKOnly built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbOKOnly (or 0) to explicitly specify that the message box has a single OK button.

      The default value of the Buttons argument is, anyway, 0. Therefore, if you omit specifying the Buttons argument, the result is also an Application modal message box with a single button (OK), which is also the default button, and no special icon style.

Macro example to create MsgBox with OK button

The following macro example creates a message box with the message “Create Excel VBA MsgBox” and a single (OK) button (vbOKOnly).

Sub MsgBoxCustomButtonsOk()
    'source: https://powerspreadsheets.com/
    'creates a message box with an OK button
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'create message box with OK button
    MsgBox Prompt:="Create Excel VBA MsgBox", Buttons:=vbOKOnly

End Sub

Effects of executing macro example to create MsgBox with OK button

The following image illustrates the results of executing the macro example. Notice that, as expected, the message box contains a single (OK) button.

Macro creates MsgBox with OK button

#6: Create MsgBox with OK and Cancel buttons

VBA code to create MsgBox with OK and Cancel buttons

To create a message box with OK and Cancel buttons using VBA, use a statement with the following structure:

OkCancelVariable = MsgBox(Prompt:=PromptString, Buttons:=vbOKCancel)

Process to create MsgBox with OK and Cancel buttons

To create a message box with OK and Cancel buttons using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox(…)).
  2. Specify that the message box should display OK and Cancel buttons (Buttons:=vbOKCancel).
  3. Assign the value returned by the MsgBox function to a variable (OkCancelVariable = MsgBox(…)).

VBA statement explanation

  1. Item: OkCancelVariable.
    • VBA construct: Variable.
    • Description: Variable you want to hold the value returned by the MsgBox function.

      If you explicitly declare OkCancelVariable, you can usually work with the Integer data type.

  2. Item: =.
    • VBA construct: Assignment (=) operator.
    • Description: The = operator assigns the Integer value returned by the MsgBox function to OkCancelVariable.
  3. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with OK and Cancel buttons using this statement structure:

      • The displayed message is PromptString.
      • The message box contains 2 buttons: OK and Cancel.
      • The value returned by the MsgBox function is 1 of the following:
        Button clicked by user Built-in constant Value
        OK vbOK 1
        Cancel vbCancel 2

      If the user presses the Esc key, the MsgBox function returns vbCancel (or 2). In other words, pressing the Esc key is the equivalent to clicking the Cancel button.

  4. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • The maximum length of PromptString is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters within PromptString.
      • PromptString can be composed of multiple lines. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  5. Item: Buttons:=vbOKCancel.
    • VBA construct: Buttons argument of the MsgBox function and vbOKCancel built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbOKCancel (or 1) to specify that the message box has OK and Cancel buttons.

Macro example to create MsgBox with OK and Cancel buttons

The following macro example does the following:

  1. Creates a message box with:
    • The message “Create Excel VBA MsgBox”; and
    • OK and Cancel buttons (vbOKCancel).
  2. Assigns the value returned by the MsgBox function to a variable (myOkCancelMsgBoxValue).
  3. Checks which value was clicked by the user:
    • If the user clicks the OK button (If myOkCancelMsgBoxValue = vbOK), the macro creates a message box with the message “You clicked OK on the message box”.
    • If the user clicks the Cancel button (ElseIf myOkCancelMsgBoxValue = vbCancel), the macro creates a message box with the message “You clicked Cancel on the message box”.
Sub MsgBoxCustomButtonsOkCancel()
    'source: https://powerspreadsheets.com/
    '(1) creates a message box with OK and Cancel buttons, and (2) executes certain statements depending on clicked button
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'declare variable to hold value returned by message box
    Dim myOkCancelMsgBoxValue As Integer

    '(1) create a message box with OK and Cancel buttons, and (2) assign value returned by message box to a variable
    myOkCancelMsgBoxValue = MsgBox(Prompt:="Create Excel VBA MsgBox", Buttons:=vbOKCancel)

    '(1) check which button was clicked (OK or Cancel), and (2) execute appropriate statements
    If myOkCancelMsgBoxValue = vbOK Then

        'display message box confirming that OK button was clicked
        MsgBox "You clicked OK on the message box"

    ElseIf myOkCancelMsgBoxValue = vbCancel Then

        'display message box confirming that Cancel button was clicked
        MsgBox "You clicked Cancel on the message box"

    End If

End Sub

Effects of executing macro example to create MsgBox with OK and Cancel buttons

The following image illustrates the results of executing the macro example. Notice that, as expected, the macro displays a second message box whose message depends on the clicked button (OK or Cancel).

Macro creates MsgBox with OK and Cancel buttons

#7: Create MsgBox with Yes and No buttons

VBA code to create MsgBox with Yes and No buttons

To create a message box with Yes and No buttons using VBA, use a statement with the following structure:

YesNoVariable = MsgBox(Prompt:=PromptString, Buttons:=vbYesNo)

Process to create MsgBox with Yes and No buttons

To create a message box with Yes and No buttons using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox(…)).
  2. Specify that the message box should display Yes and No buttons (Buttons:=vbYesNo).
  3. Assign the value returned by the MsgBox function to a variable (YesNoVariable = MsgBox(…)).

VBA statement explanation

  1. Item: YesNoVariable.
    • VBA construct: Variable.
    • Description: Variable you want to hold the value returned by the MsgBox function.

      If you explicitly declare YesNoVariable, you can usually work with the Integer data type.

  2. Item: =.
    • VBA construct: Assignment (=) operator.
    • Description: The = operator assigns the Integer value returned by the MsgBox function to YesNoVariable.
  3. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with Yes and No buttons using this statement structure:

      • The displayed message is PromptString.
      • The message box contains 2 buttons: Yes and No.
      • The value returned by the MsgBox function is 1 of the following:
        Button clicked by user Built-in constant Value
        Yes vbYes 6
        No vbNo 7
  4. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • The maximum length of PromptString is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters within PromptString.
      • PromptString can be composed of multiple lines. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  5. Item: Buttons:=vbYesNo.
    • VBA construct: Buttons argument of the MsgBox function and vbYesNo built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbYesNo (or 4) to specify that the message box has Yes and No buttons.

Macro example to create MsgBox with Yes and No buttons

The following macro example does the following:

  1. Creates a message box with:
    • The message “Create Excel VBA MsgBox”; and
    • Yes and No buttons (vbYesNo).
  2. Assigns the value returned by the MsgBox function to a variable (myYesNoMsgBoxValue).
  3. Checks which value was clicked by the user:
    • If the user clicks the Yes button (If myYesNoMsgBoxValue = vbYes), the macro creates a message box with the message “You clicked Yes on the message box”.
    • If the user clicks the No button (ElseIf myYesNoMsgBoxValue = vbNo), the macro creates a message box with the message “You clicked No on the message box”.
Sub MsgBoxCustomButtonsYesNo()
    'source: https://powerspreadsheets.com/
    '(1) creates a message box with Yes and No buttons, and (2) executes certain statements depending on clicked button
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'declare variable to hold value returned by message box
    Dim myYesNoMsgBoxValue As Integer

    '(1) create a message box with Yes and No buttons, and (2) assign value returned by message box to a variable
    myYesNoMsgBoxValue = MsgBox(Prompt:="Create Excel VBA MsgBox", Buttons:=vbYesNo)

    '(1) check which button was clicked (Yes or No), and (2) execute appropriate statements
    If myYesNoMsgBoxValue = vbYes Then

        'display message box confirming that Yes button was clicked
        MsgBox "You clicked Yes on the message box"

    ElseIf myYesNoMsgBoxValue = vbNo Then

        'display message box confirming that No button was clicked
        MsgBox "You clicked No on the message box"

    End If

End Sub

Effects of executing macro example to create MsgBox with Yes and No buttons

The following image illustrates the results of executing the macro example. Notice that, as expected, the macro displays a second message box whose message depends on the clicked button (Yes or No).

Macro creates MsgBox with Yes and No buttons

#8: Create MsgBox with Yes, No and Cancel buttons

VBA code to create MsgBox with Yes, No and Cancel buttons

To create a message box with Yes, No and Cancel buttons using VBA, use a statement with the following structure:

YesNoCancelVariable = MsgBox(Prompt:=PromptString, Buttons:=vbYesNoCancel)

Process to create MsgBox with Yes, No and Cancel buttons

To create a message box with Yes, No and Cancel buttons using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox(…)).
  2. Specify that the message box should display Yes, No and Cancel buttons (Buttons:=vbYesNoCancel).
  3. Assign the value returned by the MsgBox function to a variable (YesNoCancelVariable = MsgBox(…)).

VBA statement explanation

  1. Item: YesNoCancelVariable.
    • VBA construct: Variable.
    • Description: Variable you want to hold the value returned by the MsgBox function.

      If you explicitly declare YesNoCancelVariable, you can usually work with the Integer data type.

  2. Item: =.
    • VBA construct: Assignment (=) operator.
    • Description: The = operator assigns the Integer value returned by the MsgBox function to YesNoCancelVariable.
  3. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with Yes, No and Cancel buttons using this statement structure:

      • The displayed message is PromptString.
      • The message box contains 3 buttons: Yes, No and Cancel.
      • The value returned by the MsgBox function is 1 of the following:
        Button clicked by user Built-in constant Value
        Cancel vbCancel 2
        Yes vbYes 6
        No vbNo 7

        If the user presses the Esc key, the MsgBox function returns vbCancel (or 2). In other words, pressing the Esc key is the equivalent to clicking the Cancel button.

  4. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • The maximum length of PromptString is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters within PromptString.
      • PromptString can be composed of multiple lines. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  5. Item: Buttons:=vbYesNoCancel.
    • VBA construct: Buttons argument of the MsgBox function and vbYesNoCancel built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbYesNoCancel (or 3) to specify that the message box has Yes, No and Cancel buttons.

Macro example to create MsgBox with Yes, No and Cancel buttons

The following macro example does the following:

  1. Creates a message box with:
    • The message “Create Excel VBA MsgBox”; and
    • Yes, No and Cancel buttons (vbYesNoCancel).
  2. Assigns the value returned by the MsgBox function to a variable (myYesNoCancelMsgBoxValue).
  3. Checks which value was clicked by the user:
    • If the user clicks the Yes button (Case vbYes), the macro creates a message box with the message “You clicked Yes on the message box”.
    • If the user clicks the No button (Case vbNo), the macro creates a message box with the message “You clicked No on the message box”.
    • If the user clicks the Cancel button (Case vbCancel), the macro creates a message box with the message “You clicked Cancel on the message box”.
Sub MsgBoxCustomButtonsYesNoCancel()
    'source: https://powerspreadsheets.com/
    '(1) creates a message box with Yes, No and Cancel buttons, and (2) executes certain statements depending on clicked button
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'declare variable to hold value returned by message box
    Dim myYesNoCancelMsgBoxValue As Integer

    '(1) create a message box with Yes, No and Cancel buttons, and (2) assign value returned by message box to a variable
    myYesNoCancelMsgBoxValue = MsgBox(Prompt:="Create Excel VBA MsgBox", Buttons:=vbYesNoCancel)

    '(1) check which button was clicked (Yes, No or Cancel), and (2) execute appropriate statements
    Select Case myYesNoCancelMsgBoxValue

        'display message box confirming that Yes button was clicked
        Case vbYes: MsgBox "You clicked Yes on the message box"

        'display message box confirming that No button was clicked
        Case vbNo: MsgBox "You clicked No on the message box"

        'display message box confirming that Cancel button was clicked
        Case vbCancel: MsgBox "You clicked Cancel on the message box"

    End Select

End Sub

Effects of executing macro example to create MsgBox with Yes, No and Cancel buttons

The following image illustrates the results of executing the macro example. Notice that, as expected, the macro displays a second message box whose message depends on the clicked button (Yes, No or Cancel).

Macro creates MsgBox with Yes, No and Cancel buttons

#9: Create MsgBox with Retry and Cancel buttons

VBA code to create MsgBox with Retry and Cancel buttons

To create a message box with Retry and Cancel buttons using VBA, use a statement with the following structure:

RetryCancelVariable = MsgBox(Prompt:=PromptString, Buttons:=vbRetryCancel)

Process to create MsgBox with Retry and Cancel buttons

To create a message box with Retry and Cancel buttons using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox(…)).
  2. Specify that the message box should display Retry and Cancel buttons (Buttons:=vbRetryCancel).
  3. Assign the value returned by the MsgBox function to a variable (RetryCancelVariable = MsgBox(…)).

VBA statement explanation

  1. Item: RetryCancelVariable.
    • VBA construct: Variable.
    • Description: Variable you want to hold the value returned by the MsgBox function.

      If you explicitly declare RetryCancelVariable, you can usually work with the Integer data type.

  2. Item: =.
    • VBA construct: Assignment (=) operator.
    • Description: The = operator assigns the Integer value returned by the MsgBox function to RetryCancelVariable.
  3. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with Retry and Cancel buttons using this statement structure:

      • The displayed message is PromptString.
      • The message box contains 2 buttons: Retry and Cancel.
      • The value returned by the MsgBox function is 1 of the following:
        Button clicked by user Built-in constant Value
        Cancel vbCancel 2
        Retry vbRetry 4

      If the user presses the Esc key, the MsgBox function returns vbCancel (or 2). In other words, pressing the Esc key is the equivalent to clicking the Cancel button.

  4. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • The maximum length of PromptString is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters within PromptString.
      • PromptString can be composed of multiple lines. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  5. Item: Buttons:=vbRetryCancel.
    • VBA construct: Buttons argument of the MsgBox function and vbRetryCancel built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbRetryCancel (or 5) to specify that the message box has Retry and Cancel buttons.

Macro example to create MsgBox with Retry and Cancel buttons

The following macro example does the following:

  1. Creates a message box with:
    • The message “Create Excel VBA MsgBox”; and
    • Retry and Cancel buttons (vbRetryCancel).
  2. Assigns the value returned by the MsgBox function to a variable (myRetryCancelMsgBoxValue).
  3. Checks which value was clicked by the user:
    • If the user clicks the Retry button (If myRetryCancelMsgBoxValue = vbRetry), the macro creates a message box with the message “You clicked Retry on the message box”.
    • If the user clicks the Cancel button (ElseIf myRetryCancelMsgBoxValue = vbCancel), the macro creates a message box with the message “You clicked Cancel on the message box”.
Sub MsgBoxCustomButtonsRetryCancel()
    'source: https://powerspreadsheets.com/
    '(1) creates a message box with Retry and Cancel buttons, and (2) executes certain statements depending on clicked button
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'declare variable to hold value returned by message box
    Dim myRetryCancelMsgBoxValue As Integer

    '(1) create a message box with Retry and Cancel buttons, and (2) assign value returned by message box to a variable
    myRetryCancelMsgBoxValue = MsgBox(Prompt:="Create Excel VBA MsgBox", Buttons:=vbRetryCancel)

    '(1) check which button was clicked (Retry or Cancel), and (2) execute appropriate statements
    If myRetryCancelMsgBoxValue = vbRetry Then

        'display message box confirming that Retry button was clicked
        MsgBox "You clicked Retry on the message box"

    ElseIf myRetryCancelMsgBoxValue = vbCancel Then

        'display message box confirming that Cancel button was clicked
        MsgBox "You clicked Cancel on the message box"

    End If

End Sub

Effects of executing macro example to create MsgBox with Retry and Cancel buttons

The following image illustrates the results of executing the macro example. Notice that, as expected, the macro displays a second message box whose message depends on the clicked button (Retry or Cancel).

Macro creates MsgBox with Retry and Cancel buttons

#10: Create MsgBox with Abort, Retry and Ignore buttons

VBA code to create MsgBox with Abort, Retry and Ignore buttons

To create a message box with Abort, Retry and Ignore buttons using VBA, use a statement with the following structure:

AbortRetryIgnoreVariable = MsgBox(Prompt:=PromptString, Buttons:=vbAbortRetryIgnore)

Process to create MsgBox with Abort, Retry and Ignore buttons

To create a message box with Abort, Retry and Ignore buttons using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox(…)).
  2. Specify that the message box should display Abort, Retry and Ignore buttons (Buttons:=vbAbortRetryIgnore).
  3. Assign the value returned by the MsgBox function to a variable (AbortRetryIgnoreVariable = MsgBox(…)).

VBA statement explanation

  1. Item: AbortRetryIgnoreVariable.
    • VBA construct: Variable.
    • Description: Variable you want to hold the value returned by the MsgBox function.

      If you explicitly declare AbortRetryIgnoreVariable, you can usually work with the Integer data type.

  2. Item: =.
    • VBA construct: Assignment (=) operator.
    • Description: The = operator assigns the Integer value returned by the MsgBox function to AbortRetryIgnoreVariable.
  3. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with Abort, Retry and Ignore buttons using this statement structure:

      • The displayed message is PromptString.
      • The message box contains 3 buttons: Abort, Retry and Ignore.
      • The value returned by the MsgBox function is 1 of the following:
        Button clicked by user Built-in constant Value
        Abort vbAbort 3
        Retry vbRetry 4
        Ignore vbIgnore 5
  4. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • The maximum length of PromptString is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters within PromptString.
      • PromptString can be composed of multiple lines. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  5. Item: Buttons:=vbAbortRetryIgnore.
    • VBA construct: Buttons argument of the MsgBox function and vbAbortRetryIgnore built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbAbortRetryIgnore (or 2) to specify that the message box has Abort, Retry and Ignore buttons.

Macro example to create MsgBox with Abort, Retry and Ignore buttons

The following macro example does the following:

  1. Creates a message box with:
    • The message “Create Excel VBA MsgBox”; and
    • Abort, Retry and Ignore buttons (vbAbortRetryIgnore).
  2. Assigns the value returned by the MsgBox function to a variable (myAbortRetryIgnoreMsgBoxValue).
  3. Checks which value was clicked by the user:
    • If the user clicks the Abort button (Case vbAbort), the macro creates a message box with the message “You clicked Abort on the message box”.
    • If the user clicks the Retry button (Case vbRetry), the macro creates a message box with the message “You clicked Retry on the message box”.
    • If the user clicks the Ignore button (Case vbIgnore), the macro creates a message box with the message “You clicked Ignore on the message box”.
Sub MsgBoxCustomButtonsAbortRetryIgnore()
    'source: https://powerspreadsheets.com/
    '(1) creates a message box with Abort, Retry and Ignore buttons, and (2) executes certain statements depending on clicked button
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'declare variable to hold value returned by message box
    Dim myAbortRetryIgnoreMsgBoxValue As Integer

    '(1) create a message box with Yes, No and Cancel buttons, and (2) assign value returned by message box to a variable
    myAbortRetryIgnoreMsgBoxValue = MsgBox(Prompt:="Create Excel VBA MsgBox", Buttons:=vbAbortRetryIgnore)

    '(1) check which button was clicked (Abort, Retry or Ignore), and (2) execute appropriate statements
    Select Case myAbortRetryIgnoreMsgBoxValue

        'display message box confirming that Abort button was clicked
        Case vbAbort: MsgBox "You clicked Abort on the message box"

        'display message box confirming that Retry button was clicked
        Case vbRetry: MsgBox "You clicked Retry on the message box"

        'display message box confirming that Ignore button was clicked
        Case vbIgnore: MsgBox "You clicked Ignore on the message box"

    End Select

End Sub

Effects of executing macro example to create MsgBox with Abort, Retry and Ignore buttons

The following image illustrates the results of executing the macro example. Notice that, as expected, the macro displays a second message box whose message depends on the clicked button (Abort, Retry or Ignore).

Macro creates MsgBox with Abort, Retry and Ignore buttons

#11: Create MsgBox with critical style

VBA code to create MsgBox with critical style

To create a message box with the critical icon style using VBA, use a statement with the following structure:

MsgBox Prompt:=PromptString, Buttons:=vbCritical

Process to create MsgBox with critical style

To create a message box with the critical icon style using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox …).
  2. Specify that the message box should use the critical icon style (Buttons:=vbCritical).

VBA statement explanation

  1. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with a critical icon style using this statement structure:

      • The displayed message is PromptString.
      • The message box contains a single button: OK. For purposes of including other custom button layouts, please refer to the appropriate sections of this Tutorial.
      • The value returned by the MsgBox function is vbOK (or 1). For purposes of assigning the value returned by the MsgBox function to a variable, please refer to the appropriate section of this Tutorial.
  2. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • The maximum length of PromptString is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters within PromptString.
      • PromptString can be composed of multiple lines. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  3. Item: Buttons:=vbCritical.
    • VBA construct: Buttons argument of the MsgBox function and vbCritical built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbCritical (or 16) to specify that the message box uses the critical icon style and, therefore, displays a Critical Message icon.

Macro example to create MsgBox with critical style

The following macro example creates a message box with:

  • The message “Create Excel VBA MsgBox”; and
  • The critical message icon style (vbCritical), which results in the Critical Message icon being displayed.
Sub MsgBoxCriticalStyle()
    'source: https://powerspreadsheets.com/
    'creates a message box with a critical message icon style
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'create a message box with a critical message icon style
    MsgBox Prompt:="Create Excel VBA MsgBox", Buttons:=vbCritical

End Sub

Effects of executing macro example to create MsgBox with critical style

The following image illustrates the results of executing the macro example. Notice that, as expected, the message box uses the critical message icon style.

Macro creates MsgBox with critical style icon

#12: Create MsgBox with question style

VBA code to create MsgBox with question style

To create a message box with the question icon style using VBA, use a statement with the following structure:

MsgBox Prompt:=PromptString, Buttons:=vbQuestion

Process to create MsgBox with question style

To create a message box with the question icon style using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox …).
  2. Specify that the message box should use the question icon style (Buttons:=vbQuestion).

VBA statement explanation

  1. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with the question icon style using this statement structure:

      • The displayed message is PromptString.
      • The message box contains a single button: OK. For purposes of including other custom button layouts, please refer to the appropriate sections of this Tutorial.
      • The value returned by the MsgBox function is vbOK (or 1). For purposes of assigning the value returned by the MsgBox function to a variable, please refer to the appropriate section of this Tutorial.
  2. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • The maximum length of PromptString is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters within PromptString.
      • PromptString can be composed of multiple lines. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  3. Item: Buttons:=vbQuestion.
    • VBA construct: Buttons argument of the MsgBox function and vbQuestion built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbQuestion (or 32) to specify that the message box uses the question icon style and, therefore, displays a Warning Query icon.

Macro example to create MsgBox with question style

The following macro example creates a message box with:

  • The message “Create Excel VBA MsgBox”; and
  • The question icon style (vbQuestion), which results in the Warning Query icon being displayed.
Sub MsgBoxQuestionStyle()
    'source: https://powerspreadsheets.com/
    'creates a message box with the question icon style
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'create a message box with the question icon style
    MsgBox Prompt:="Create Excel VBA MsgBox", Buttons:=vbQuestion

End Sub

Effects of executing macro example to create MsgBox with question style

The following image illustrates the results of executing the macro example. Notice that, as expected, the message box uses the question icon style.

Macro creates MsgBox with question style icon

#13: Create MsgBox with exclamation style

VBA code to create MsgBox with exclamation style

To create a message box with the exclamation icon style using VBA, use a statement with the following structure:

MsgBox Prompt:=PromptString, Buttons:=vbExclamation

Process to create MsgBox with exclamation style

To create a message box with the exclamation icon style using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox …).
  2. Specify that the message box should use the exclamation icon style (Buttons:=vbExclamation).

VBA statement explanation

  1. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with an exclamation icon style using this statement structure:

      • The displayed message is PromptString.
      • The message box contains a single button: OK. For purposes of including other custom button layouts, please refer to the appropriate sections of this Tutorial.
      • The value returned by the MsgBox function is vbOK (or 1). For purposes of assigning the value returned by the MsgBox function to a variable, please refer to the appropriate section of this Tutorial.
  2. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • The maximum length of PromptString is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters within PromptString.
      • PromptString can be composed of multiple lines. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  3. Item: Buttons:=vbExclamation.
    • VBA construct: Buttons argument of the MsgBox function and vbExclamation built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbExclamation (or 48) to specify that the message box uses the exclamation icon style and, therefore, displays a Warning Message icon.

Macro example to create MsgBox with exclamation style

The following macro example creates a message box with:

  • The message “Create Excel VBA MsgBox”; and
  • The exclamation icon style (vbExclamation), which results in the Warning Message icon being displayed.
Sub MsgBoxExclamationStyle()
    'source: https://powerspreadsheets.com/
    'creates a message box with a warning message icon style
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'create a message box with an exclamation icon style
    MsgBox Prompt:="Create Excel VBA MsgBox", Buttons:=vbExclamation

End Sub

Effects of executing macro example to create MsgBox with exclamation style

The following image illustrates the results of executing the macro example. Notice that, as expected, the message box uses the exclamation icon style.

Macro creates MsgBox with exclamation style icon

#14: Create MsgBox with information style

VBA code to create MsgBox with information style

To create a message box with the information icon style using VBA, use a statement with the following structure:

MsgBox Prompt:=PromptString, Buttons:=vbInformation

Process to create MsgBox with information style

To create a message box with the information icon style using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox …).
  2. Specify that the message box should use the information icon style (Buttons:=vbInformation).

VBA statement explanation

  1. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with an information icon style using this statement structure:

      • The displayed message is PromptString.
      • The message box contains a single button: OK. For purposes of including other custom button layouts, please refer to the appropriate sections of this Tutorial.
      • The value returned by the MsgBox function is vbOK (or 1). For purposes of assigning the value returned by the MsgBox function to a variable, please refer to the appropriate section of this Tutorial.
  2. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • The maximum length of PromptString is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters within PromptString.
      • PromptString can be composed of multiple lines. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  3. Item: Buttons:=vbInformation.
    • VBA construct: Buttons argument of the MsgBox function and vbInformation built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbInformation (or 64) to specify that the message box uses the information icon style and, therefore, displays an Information Message icon.

Macro example to create MsgBox with information style

The following macro example creates a message box with:

  • The message “Create Excel VBA MsgBox”; and
  • The information icon style (vbInformation), which results in the Information Message icon being displayed.
Sub MsgBoxInformationStyle()
    'source: https://powerspreadsheets.com/
    'creates a message box with an information message icon style
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'create a message box with an information message icon style
    MsgBox Prompt:="Create Excel VBA MsgBox", Buttons:=vbInformation

End Sub

Effects of executing macro example to create MsgBox with information style

The following image illustrates the results of executing the macro example. Notice that, as expected, the message box uses the information message icon style.

Macro creates MsgBox with information style icon

#15: Create MsgBox where first button is default

VBA code to create MsgBox where first button is default

To create a message box where the first button is the default with VBA, use a statement with the following structure:

CustomButtons1Variable = MsgBox(Prompt:=PromptString, Buttons:=ButtonsExpression1 + vbDefaultButton1)

Process to create MsgBox where first button is default

To create a message box where the first button is the default with VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox(…)).
  2. Specify the buttons to be displayed in the message box and, explicitly, specify that the first button is the default one (Buttons:=ButtonsExpression1 + vbDefaultButton1).
  3. Assign the value returned by the MsgBox function to a variable (CustomButtons1Variable = MsgBox(…)).

VBA statement explanation

  1. Item: CustomButtons1Variable.
    • VBA construct: Variable.
    • Description: Variable you want to hold the value returned by the MsgBox function.

      If you explicitly declare CustomButtons1Variable, you can usually work with the Integer data type.

  2. Item: =.
    • VBA construct: Assignment (=) operator.
    • Description: The = operator assigns the Integer value returned by the MsgBox function to CustomButtons1Variable.
  3. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box where the first button is the default using this statement structure:

      • The displayed message is PromptString.
      • The message box contains the buttons specified by ButtonsExpression1. For purposes of working with the main custom button layouts, please refer to the appropriate sections of this Tutorial.
  4. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • The maximum length of PromptString is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters within PromptString.
      • PromptString can be composed of multiple lines. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  5. Item: Buttons:=ButtonsExpression1 + vbDefaultButton1.
    • VBA construct: Buttons argument of the MsgBox function.
    • Description: Use the Buttons argument of the MsgBox function to specify the following:
      • Number and type of buttons displayed in the message box.
      • Icon style for the message box.
      • That the first button in the message box is the default.
      • Modality of the message box.
  6. Item: ButtonsExpression1.
    • VBA construct: Numeric expression partially specifying the value assigned to the Buttons argument.
    • Description: Specify ButtonsExpression1 as a sum of the following 3 groups of values or built-in constants:
      • Values or built-in constants that specify the number and type of buttons displayed in the message box, as follows:
        Built-in constant Value Description
        vbOKOnly 0 Message box with only OK button
        vbOKCancel 1 Message box with OK and Cancel buttons
        vbAbortRetryIgnore 2 Message box with Abort, Retry and Ignore buttons
        vbYesNoCancel 3 Message box with Yes, No and Cancel buttons
        vbYesNo 4 Message box with Yes and No buttons
        vbRetryCancel 5 Message box with Retry and Cancel buttons

        For purposes of working with these different custom button layouts, please refer to the appropriate sections of this Tutorial.

      • Values or built-in constants that specify the icon style of the message box, as follows:
        Built-in constant Value Description
        vbCritical 16 Message box with Critical Message icon
        vbQuestion 32 Message box with Warning Query icon
        vbExclamation 48 Message box with Warning Message icon
        vbInformation 64 Message box with Information Message icon

        For purposes of working with these different icon styles, please refer to the appropriate sections of this Tutorial.

      • Values or built-in constants that specify the modality of the message box, as follows:
        Built-in constant Value Description
        vbApplicationModal 0 Application modal message box
        vbSystemModal 4096 System modal message box

        For purposes of working with this different modality options, please refer to the appropriate sections of this Tutorial.

      When specifying ButtonsExpression1:

      • Specify ButtonsExpression1 as a sum of the applicable values or built-in constants.
      • Omit the values from the groups you don’t specify.
      • Use a maximum of 1 value from each of these 3 groups.
      • In addition to the values and built-in constants I list above, the Buttons argument accepts the following 4 settings:
        Built-in constant Value Description
        vbMsgBoxHelpButton 16384 Message box with an additional Help button.

        The MsgBox function also accepts a (optional) helpfile and context arguments that specify the applicable Help file and Help context number.

        Clicking on the Help button results in the applicable help being provided. The MsgBox function only returns a value when the user clicks 1 of the other buttons in the message box.

        vbMsgBoxSetForeground 65536 Message box is the foreground window
        vbMsgBoxRight 524288 Text within the message box is aligned to the right
        vbMsgBoxRtlReading 1048576 Text within the message box is displayed as right-to-left reading on Hebrew and Arabic systems
  7. Item: vbDefaultButton1.
    • VBA construct: vbDefaultButton1 built-in constant.
    • Description: Include vbDefaultButton1 (or 0) in the numeric expression assigned to the Buttons argument to specify that the first button of the message box is the default button.

      The default value of the Buttons argument is, anyway, 0. Therefore, if you omit specifying the Buttons argument, the result is an Application modal message box with a single button (OK), which is also the default button, and no special icon style.

Macro example to create MsgBox where first button is default

The following macro example does the following:

  1. Creates a message box with:
    • The message “Create Excel VBA MsgBox”; and
    • Yes and No buttons (vbYesNo). The first button (vbDefaultButton1) is explicitly set as the default.
  2. Assigns the value returned by the MsgBox function to a variable (myCustomButtonsDefault1MsgBoxValue).
  3. Checks which value was clicked by the user:
    • If the user clicks the Yes button (If myCustomButtonsDefault1MsgBoxValue = vbYes), the macro creates a message box with the message “You clicked Yes on the message box”.
    • If the user clicks the No button (ElseIf myCustomButtonsDefault1MsgBoxValue = vbNo), the macro creates a message box with the message “You clicked No on the message box”.
Sub MsgBoxCustomButtonsDefault1()
    'source: https://powerspreadsheets.com/
    '(1) creates a message box with Yes and No buttons, (2) specifies that first button (Yes) is default, and (3) executes certain statements depending on clicked button
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'declare variable to hold value returned by message box
    Dim myCustomButtonsDefault1MsgBoxValue As Integer

    '(1) create a message box with Yes and No buttons where the first button (Yes) is the default, and (2) assign value returned by message box to a variable
    myCustomButtonsDefault1MsgBoxValue = MsgBox(Prompt:="Create Excel VBA MsgBox", Buttons:=vbYesNo + vbDefaultButton1)

    '(1) check which button was clicked (Yes or No), and (2) execute appropriate statements
    If myCustomButtonsDefault1MsgBoxValue = vbYes Then

        'display message box confirming that Yes button was clicked
        MsgBox "You clicked Yes on the message box"

    ElseIf myCustomButtonsDefault1MsgBoxValue = vbNo Then

        'display message box confirming that No button was clicked
        MsgBox "You clicked No on the message box"

    End If

End Sub

Effects of executing macro example to create MsgBox where first button is default

The following image illustrates the results of executing the macro example. Notice that, as expected, the first button in the message box is the default.

Macro creates MsgBox where first button is default

#16: Create MsgBox where second button is default

VBA code to create MsgBox where second button is default

To create a message box where the second button is the default with VBA, use a statement with the following structure:

CustomButtons2Variable = MsgBox(Prompt:=PromptString, Buttons:=ButtonsExpression1 + vbDefaultButton2)

Process to create MsgBox where second button is default

To create a message box where the second button is the default with VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox(…)).
  2. Specify the buttons to be displayed in the message box and, explicitly, specify that the second button is the default one (Buttons:=ButtonsExpression1 + vbDefaultButton2).
  3. Assign the value returned by the MsgBox function to a variable (CustomButtons2Variable = MsgBox(…)).

VBA statement explanation

  1. Item: CustomButtons2Variable.
    • VBA construct: Variable.
    • Description: Variable you want to hold the value returned by the MsgBox function.

      If you explicitly declare CustomButtons2Variable, you can usually work with the Integer data type.

  2. Item: =.
    • VBA construct: Assignment (=) operator.
    • Description: The = operator assigns the Integer value returned by the MsgBox function to CustomButtons2Variable.
  3. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box where the second button is the default using this statement structure:

      • The displayed message is PromptString.
      • The message box contains the buttons specified by ButtonsExpression1. For purposes of working with the main custom button layouts, please refer to the appropriate sections of this Tutorial.
  4. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • The maximum length of PromptString is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters within PromptString.
      • PromptString can be composed of multiple lines. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  5. Item: Buttons:=ButtonsExpression1 + vbDefaultButton2.
    • VBA construct: Buttons argument of the MsgBox function.
    • Description: Use the Buttons argument of the MsgBox function to specify the following:
      • Number and type of buttons displayed in the message box.
      • Icon style for the message box.
      • That the second button in the message box is the default.
      • Modality of the message box.
  6. Item: ButtonsExpression1.
    • VBA construct: Numeric expression partially specifying the value assigned to the Buttons argument.
    • Description: Specify ButtonsExpression1 as a sum of the following 3 groups of values or built-in constants:
      • Values or built-in constants that specify the number and type of buttons displayed in the message box, as follows:
        Built-in constant Value Description
        vbOKOnly 0 Message box with only OK button
        vbOKCancel 1 Message box with OK and Cancel buttons
        vbAbortRetryIgnore 2 Message box with Abort, Retry and Ignore buttons
        vbYesNoCancel 3 Message box with Yes, No and Cancel buttons
        vbYesNo 4 Message box with Yes and No buttons
        vbRetryCancel 5 Message box with Retry and Cancel buttons

        Usually, when creating a message box where the second button is the default, you don’t work with vbOKOnly (0). For purposes of working with these different custom button layouts, please refer to the appropriate sections of this Tutorial.

      • Values or built-in constants that specify the icon style of the message box, as follows:
        Built-in constant Value Description
        vbCritical 16 Message box with Critical Message icon
        vbQuestion 32 Message box with Warning Query icon
        vbExclamation 48 Message box with Warning Message icon
        vbInformation 64 Message box with Information Message icon

        For purposes of working with these different icon styles, please refer to the appropriate sections of this Tutorial.

      • Values or built-in constants that specify the modality of the message box, as follows:
        Built-in constant Value Description
        vbApplicationModal 0 Application modal message box
        vbSystemModal 4096 System modal message box

        For purposes of working with this different modality options, please refer to the appropriate sections of this Tutorial.

      When specifying ButtonsExpression1:

      • Specify ButtonsExpression1 as a sum of the applicable values or built-in constants.
      • Omit the values from the groups you don’t specify.
      • Use a maximum of 1 value from each of these 3 groups.
      • In addition to the values and built-in constants I list above, the Buttons argument accepts the following 4 settings:
        Built-in constant Value Description
        vbMsgBoxHelpButton 16384 Message box with an additional Help button.

        The MsgBox function also accepts a (optional) helpfile and context arguments that specify the applicable Help file and Help context number.

        Clicking on the Help button results in the applicable help being provided. The MsgBox function only returns a value when the user clicks 1 of the other buttons in the message box.

        vbMsgBoxSetForeground 65536 Message box is the foreground window
        vbMsgBoxRight 524288 Text within the message box is aligned to the right
        vbMsgBoxRtlReading 1048576 Text within the message box is displayed as right-to-left reading on Hebrew and Arabic systems
  7. Item: vbDefaultButton2.
    • VBA construct: vbDefaultButton2 built-in constant.
    • Description: Include vbDefaultButton2 (or 256) in the numeric expression assigned to the Buttons argument to specify that the second button of the message box is the default button.

Macro example to create MsgBox where second button is default

The following macro example does the following:

  1. Creates a message box with:
    • The message “Create Excel VBA MsgBox”; and
    • Yes and No buttons (vbYesNo). The second button (vbDefaultButton2) is set as the default.
  2. Assigns the value returned by the MsgBox function to a variable (myCustomButtonsDefault2MsgBoxValue).
  3. Checks which value was clicked by the user:
    • If the user clicks the Yes button (If myCustomButtonsDefault2MsgBoxValue = vbYes), the macro creates a message box with the message “You clicked Yes on the message box”.
    • If the user clicks the No button (ElseIf myCustomButtonsDefault2MsgBoxValue = vbNo), the macro creates a message box with the message “You clicked No on the message box”.
Sub MsgBoxCustomButtonsDefault2()
    'source: https://powerspreadsheets.com/
    '(1) creates a message box with Yes and No buttons, (2) specifies that second button (No) is default, and (3) executes certain statements depending on clicked button
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'declare variable to hold value returned by message box
    Dim myCustomButtonsDefault2MsgBoxValue As Integer

    '(1) create a message box with Yes and No buttons where the second button (No) is the default, and (2) assign value returned by message box to a variable
    myCustomButtonsDefault2MsgBoxValue = MsgBox(Prompt:="Create Excel VBA MsgBox", Buttons:=vbYesNo + vbDefaultButton2)

    '(1) check which button was clicked (Yes or No), and (2) execute appropriate statements
    If myCustomButtonsDefault2MsgBoxValue = vbYes Then

        'display message box confirming that Yes button was clicked
        MsgBox "You clicked Yes on the message box"

    ElseIf myCustomButtonsDefault2MsgBoxValue = vbNo Then

        'display message box confirming that No button was clicked
        MsgBox "You clicked No on the message box"

    End If

End Sub

Effects of executing macro example to create MsgBox where second button is default

The following image illustrates the results of executing the macro example. Notice that, as expected, the second button in the message box is the default.

Macro creates MsgBox where second button is default

#17: Create MsgBox where third button is default

VBA code to create MsgBox where third button is default

To create a message box where the third button is the default with VBA, use a statement with the following structure:

CustomButtons3Variable = MsgBox(Prompt:=PromptString, Buttons:=ButtonsExpression + vbDefaultButton3)

Process to create MsgBox where third button is default

To create a message box where the third button is the default with VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox(…)).
  2. Specify the buttons to be displayed in the message box and, explicitly, specify that the third button is the default one (Buttons:=ButtonsExpression1 + vbDefaultButton3).
  3. Assign the value returned by the MsgBox function to a variable (CustomButtons3Variable = MsgBox(…)).

VBA statement explanation

  1. Item: CustomButtons3Variable.
    • VBA construct: Variable.
    • Description: Variable you want to hold the value returned by the MsgBox function.

      If you explicitly declare CustomButtons3Variable, you can usually work with the Integer data type.

  2. Item: =.
    • VBA construct: Assignment (=) operator.
    • Description: The = operator assigns the Integer value returned by the MsgBox function to CustomButtons3Variable.
  3. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box where the third button is the default using this statement structure:

      • The displayed message is PromptString.
      • The message box contains the buttons specified by ButtonsExpression1. For purposes of working with the main custom button layouts, please refer to the appropriate sections of this Tutorial.
  4. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • The maximum length of PromptString is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters within PromptString.
      • PromptString can be composed of multiple lines. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  5. Item: Buttons:=ButtonsExpression1 + vbDefaultButton3.
    • VBA construct: Buttons argument of the MsgBox function.
    • Description: Use the Buttons argument of the MsgBox function to specify the following:
      • Number and type of buttons displayed in the message box.
      • Icon style for the message box.
      • That the third button in the message box is the default.
      • Modality of the message box.
  6. Item: ButtonsExpression1.
    • VBA construct: Numeric expression partially specifying the value assigned to the Buttons argument.
    • Description: Specify ButtonsExpression1 as a sum of the following 3 groups of values or built-in constants:
      • Values or built-in constants that specify the number and type of buttons displayed in the message box, as follows:
        Built-in constant Value Description
        vbOKCancel 1 Message box with OK and Cancel buttons
        vbAbortRetryIgnore 2 Message box with Abort, Retry and Ignore buttons
        vbYesNoCancel 3 Message box with Yes, No and Cancel buttons
        vbYesNo 4 Message box with Yes and No buttons
        vbRetryCancel 5 Message box with Retry and Cancel buttons

        Usually, when creating a message box where the third button is the default, you work with either vbAbortRetryIgnore (2) or vbYesNoCancel (3). For purposes of working with these different custom button layouts, please refer to the appropriate sections of this Tutorial.

      • Values or built-in constants that specify the icon style of the message box, as follows:
        Built-in constant Value Description
        vbCritical 16 Message box with Critical Message icon
        vbQuestion 32 Message box with Warning Query icon
        vbExclamation 48 Message box with Warning Message icon
        vbInformation 64 Message box with Information Message icon

        For purposes of working with these different icon styles, please refer to the appropriate sections of this Tutorial.

      • Values or built-in constants that specify the modality of the message box, as follows:
        Built-in constant Value Description
        vbApplicationModal 0 Application modal message box
        vbSystemModal 4096 System modal message box

        For purposes of working with this different modality options, please refer to the appropriate sections of this Tutorial.

      When specifying ButtonsExpression1:

      • Specify ButtonsExpression1 as a sum of the applicable values or built-in constants.
      • Omit the values from the groups you don’t specify.
      • Use a maximum of 1 value from each of these 3 groups.
      • In addition to the values and built-in constants I list above, the Buttons argument accepts the following 4 settings:
        Built-in constant Value Description
        vbMsgBoxHelpButton 16384 Message box with an additional Help button.

        The MsgBox function also accepts a (optional) helpfile and context arguments that specify the applicable Help file and Help context number.

        Clicking on the Help button results in the applicable help being provided. The MsgBox function only returns a value when the user clicks 1 of the other buttons in the message box.

        vbMsgBoxSetForeground 65536 Message box is the foreground window
        vbMsgBoxRight 524288 Text within the message box is aligned to the right
        vbMsgBoxRtlReading 1048576 Text within the message box is displayed as right-to-left reading on Hebrew and Arabic systems
  7. Item: vbDefaultButton3.
    • VBA construct: vbDefaultButton3 built-in constant.
    • Description: Include vbDefaultButton3 (or 512) in the numeric expression assigned to the Buttons argument to specify that the third button of the message box is the default button.

Macro example to create MsgBox where third button is default

The following macro example does the following:

  1. Creates a message box with:
    • The message “Create Excel VBA MsgBox”; and
    • Yes, No and Cancel buttons (vbYesNoCancel). The third button (vbDefaultButton3) is set as the default.
  2. Assigns the value returned by the MsgBox function to a variable (myCustomButtonsDefault3MsgBoxValue).
  3. Checks which value was clicked by the user:
    • If the user clicks the Yes button (Case vbYes), the macro creates a message box with the message “You clicked Yes on the message box”.
    • If the user clicks the No button (Case vbNo), the macro creates a message box with the message “You clicked No on the message box”.
    • If the user clicks the Cancel button (Case vbCancel), the macro creates a message box with the message “You clicked Cancel on the message box”.
Sub MsgBoxCustomButtonsDefault3()
    'source: https://powerspreadsheets.com/
    '(1) creates a message box with Yes, No and Cancel buttons, (2) specifies that third button (Cancel) is default, and (3) executes certain statements depending on clicked button
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'declare variable to hold value returned by message box
    Dim myCustomButtonsDefault3MsgBoxValue As Integer

    '(1) create a message box with Yes, No and Cancel buttons where the third button (Cancel) is the default, and (2) assign value returned by message box to a variable
    myCustomButtonsDefault3MsgBoxValue = MsgBox(Prompt:="Create Excel VBA MsgBox", Buttons:=vbYesNoCancel + vbDefaultButton3)

    '(1) check which button was clicked (Yes, No or Cancel), and (2) execute appropriate statements
    Select Case myCustomButtonsDefault3MsgBoxValue

        'display message box confirming that Yes button was clicked
        Case vbYes: MsgBox "You clicked Yes on the message box"

        'display message box confirming that No button was clicked
        Case vbNo: MsgBox "You clicked No on the message box"

        'display message box confirming that Cancel button was clicked
        Case vbCancel: MsgBox "You clicked Cancel on the message box"

    End Select

End Sub

Effects of executing macro example to create MsgBox where third button is default

The following image illustrates the results of executing the macro example. Notice that, as expected, the third button in the message box is the default.

Macro creates MsgBox where third button is default

#18: Create Application modal MsgBox

VBA code to create Application modal MsgBox

To create an Application modal message box with VBA, use a statement with the following structure:

MsgBox Prompt:=PromptString, Buttons:=vbApplicationModal

Process to create Application modal MsgBox

To create an Application modal message box with VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox …).
  2. Specify that the message box should be Application modal (Buttons:=vbApplicationModal).

VBA statement explanation

  1. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create an Application modal message box using this statement structure:

      • The displayed message is PromptString.
      • The message box contains a single button: OK. For purposes of including other custom button layouts, please refer to the appropriate sections of this Tutorial.
      • The value returned by the MsgBox function is vbOK (or 1). For purposes of assigning the value returned by the MsgBox function to a variable, please refer to the appropriate section of this Tutorial.
  2. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • The maximum length of PromptString is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters within PromptString.
      • PromptString can be composed of multiple lines. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  3. Item: Buttons:=vbApplicationModal.
    • VBA construct: Buttons argument of the MsgBox function and vbApplicationModal built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbApplicationModal (or 0) to specify that the message box is Application modal. When a message box is Application modal, the user must respond to the message box prior to working again with the Excel Application.

      The default value of the Buttons argument is, anyway, 0. Therefore, if you omit specifying the Buttons argument, the result is also an Application modal message box with a single button (OK), which is also the default button, and no special icon style.

Macro example to create Application modal MsgBox

The following macro example creates an Application modal (vbApplicationModal) message box with the message “Create Excel VBA MsgBox”.

Sub MsgBoxApplicationModal()
    'source: https://powerspreadsheets.com/
    'creates an Application modal message box
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'create an Application modal message box
    MsgBox Prompt:="Create Excel VBA MsgBox", Buttons:=vbApplicationModal

End Sub

Effects of executing macro example to create Application modal MsgBox

The following image illustrates the results of executing the macro example. This message box is Application modal.

Macro creates Application modal MsgBox

#19: Create System modal MsgBox

VBA code to create System modal MsgBox

To create a System modal message box with VBA, use a statement with the following structure:

MsgBox Prompt:=PromptString, Buttons:=vbSystemModal

Process to create System modal MsgBox

To create a System modal message box with VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox …).
  2. Specify that the message box should be System modal (Buttons:=vbSystemModal).

VBA statement explanation

  1. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a System modal message box using this statement structure:

      • The displayed message is PromptString.
      • The message box contains a single button: OK. For purposes of including other custom button layouts, please refer to the appropriate sections of this Tutorial.
      • The value returned by the MsgBox function is vbOK (or 1). For purposes of assigning the value returned by the MsgBox function to a variable, please refer to the appropriate section of this Tutorial.
  2. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • The maximum length of PromptString is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters within PromptString.
      • PromptString can be composed of multiple lines. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  3. Item: Buttons:=vbSystemModal.
    • VBA construct: Buttons argument of the MsgBox function and vbSystemModal built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbSystemModal (or 4096) to specify that the message box is System modal. When a message box is System modal, the user must respond to the message box prior to working with any application.

Macro example to create System modal MsgBox

The following macro example creates a System modal (vbSystemModal) message box with the message “Create Excel VBA MsgBox”.

Sub MsgBoxSystemModal()
    'source: https://powerspreadsheets.com/
    'creates a System modal message box
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'create a System modal message box
    MsgBox Prompt:="Create Excel VBA MsgBox", Buttons:=vbSystemModal

End Sub

Effects of executing macro example to create System modal MsgBox

The following image illustrates the results of executing the macro example. This message box is System modal.

Macro creates System modal MsgBox

Learn more about creating message boxes with VBA

Workbook example used in this Excel VBA MsgBox Tutorial

You can get immediate free access to the example workbook that accompanies this Excel VBA MsgBox Tutorial by clicking the button below.

Get immediate free access to the Excel VBA MsgBox Tutorial workbook example

Понравилась статья? Поделить с друзьями:
  • Excel макрос выбрать строку
  • Excel макрос выбрать столбец
  • Excel макрос выбрать диапазон
  • Excel макрос выбрать данные
  • Excel макрос выбрать все листы