Vba for excel msgbox

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)

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

The VBA MsgBox function is used to display messages to the user in the form of a message box.

We can configure the message box to provide the user with a number of different buttons such as Yes, No, Ok, Retry, Abort, Ignore and Cancel. The MsgBox function will then return the button that was clicked.

Related Links

VBA Userforms

Basic VBA MsgBox Examples

In most cases, you will use MsgBox to simply display a message or to ask the user to click Yes/No or Ok/Cancel. The following code shows how to display a simple message box:

' https://excelmacromastery.com/
Sub BasicMessageBox()

    ' Basic message
    MsgBox "There is no data on this worksheet "

    ' Basic message with "Error" as the title
    MsgBox "There is no data on this worksheet ", , "Error"

End Sub

MsgBox Example

VBA MsgBox Parameters

The parameters of the message box are as follows:

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

prompt – This is the message text that will be displayed.

buttons[optional] – This parameter does many things including setting the buttons, icons, select button, modal type etc. If this parameter is not used a message box with the Ok button and no icon is displayed. See the next section for more about this parameter.

title[optional] – this is the title that will appear at the top of the message box. The default is “Microsoft Excel”.

helpfile, context[optional] – These parameters are used to reference a help file and location of specific help text. It is very unlikely you use this unless you are creating an application for a third party and help files are a requirement.

VBA MsgBox Return Values

The following are all the return values for the MsgBox function:

vbOk
vbCancel
vbAbort
vbRetry
vbIgnore
vbYes
vbNo

Each of these values represents a button that was clicked.

VBA MsgBox Yes No

We can use the message box to get a simple response from the user. For example, we can ask the user a question and they can respond by clicking on the Yes or No button. The return value from the MsgBox function tells us which button was clicked.

VBA MsgBox

If we want to get a Yes/No response from the user we can do it with the following code:

' https://excelmacromastery.com/
Sub MessagesYesNoWithResponse()

    ' Display a messagebox based on the response
    If MsgBox("Do you wish to continue? ", vbYesNo) = vbYes Then
        MsgBox "The user clicked Yes"
    Else
        MsgBox "The user clicked No"
    End If

End Sub

Note: When we return a value from the message box we must use parenthesis around the parameters or we will get the “Expected end of statement” error.

We can also use a variable to store the response from the MsgBox. We would normally do this if we want to use the response more than once. For example, if there were three buttons:

' https://excelmacromastery.com/
Sub Msgbox_AbortRetryIgnore()

    Dim resp As VbMsgBoxResult
    ' Store MsgBox response in a variable
    resp = MsgBox("Do you wish to continue? ", vbAbortRetryIgnore)
    
    ' Display Ok/Cancel buttons and get response
    If resp = vbAbort Then
        MsgBox "The user clicked Abort"
    ElseIf resp = vbRetry Then
        MsgBox "The user clicked Retry"
    ElseIf resp = vbIgnore Then
        MsgBox "The user clicked Ignore"
    End If

End Sub

VBA MsgBox Button Constants

The button parameter of MsgBox allows us to configure the message box in many ways. The table below shows the different options:

Constant Group Type Description
vbOKOnly 1 Buttons Ok button.
vbOKCancel 1 Buttons Ok and cancel buttons.
vbAbortRetryIgnore 1 Buttons Abort, Retry and Ignore buttons.
vbYesNoCancel 1 Buttons Yes, No and Cancel buttons.
vbYesNo 1 Buttons Yes and No buttons.
vbRetryCancel 1 Buttons Retry and Cancel buttons.
vbCritical 2 Icon Critical Message icon.
vbQuestion 2 Icon Question mark icon.
vbExclamation 2 Icon Warning Message icon.
vbInformation 2 Icon Information Message icon.
vbDefaultButton1 3 Default button Set button 1 to be selected.
vbDefaultButton2 3 Default button Set button 2 to be selected.
vbDefaultButton3 3 Default button Set button 3 to be selected.
vbDefaultButton4 3 Default button Set button 4 to be selected. Note that there will only be four buttons if the help button is included with vbAbortRetryIgnore or vbYesNoCancel.
vbApplicationModal 4 Modal Cannot access Excel while the button is displayed. Msgbox is only displayed when Excel is the active application.
vbSystemModal 4 Modal Same as vbApplicationModal but the message box is displayed in front of all applications.
vbMsgBoxHelpButton 5 Other Adds a help button
vbMsgBoxSetForeground 5 Other Sets the message box windows to be the foreground window
vbMsgBoxRight 5 Other Right aligns the text.
vbMsgBoxRtlReading 5 Other Specifies text should appear as right-to-left reading on Hebrew and Arabic systems.

These constants work as follows:

  1. The constants in group 1 are used to select the buttons.
  2. The constants in group 2 are used to select icons.
  3. The constants in group 3 are used to select which button is highlighted when the message box appears.
  4. The constants in group 4 are used to set the modal type of the message box.
  5. The constants in group 5 are used for various settings.

When we use MsgBox, we can combine items from each group by using the plus sign. For example:

MsgBox "Example 1" ,vbOkCancel + vbCritical + vbDefaultButton1 + vbApplicationModal

This displays the message box with the Ok and Cancel button, the critical message icon, with the Ok button highlighted and the message box will display only when Excel is the active application.

MsgBox "Example 2", vbYesNo + vbQuestion + vbDefaultButton2 + vbSystemModal

This displays the message box with the Yes and No button, the warning query icon, with the No button highlighted and the message box will display in front of all applications.

Important: Each time we use the MsgBox function we can only select one of each:

  1. button type
  2. icon type
  3. default button
  4. modal type

In other words, we can only select one item from each of the first 4 groups.

The next section shows some more examples of using the message box.

VBA MsgBox Examples

The following examples show to display the various icons with the Yes and No buttons:

  ' Yes/No buttons with Critical icon and No button selected
 resp = MsgBox("Do you wish to continue", vbYesNo + vbCritical)
 
 ' Yes/No buttons with Warning Query icon and Yes button selected
 resp = MsgBox("Do you wish to continue", vbYesNo + vbQuestion)
 
 ' Yes/No buttons with Warning Message icon and Yes button selected
 resp = MsgBox("Do you wish to continue", vbYesNo + vbExclamation)

 ' Yes/No button with Information Message icon and Cancel button selected
 resp = MsgBox("Do you wish to continue", vbYesNo + vbInformation)

The following examples show the Abort/Retry/Ignore button plus the help button with different buttons selected:

' Abort/Retry/Ignore button with the Help button displayed and Abort selected
resp = MsgBox("Error", vbAbortRetryIgnore + vbDefaultButton1 + vbMsgBoxHelpButton)

' Abort/Retry/Ignore button with the help button displayed and Retry selected
resp = MsgBox("Error", vbAbortRetryIgnore + vbDefaultButton2 + vbMsgBoxHelpButton)

' Abort/Retry/Ignore button with the Help button displayed and Ignore selected
resp = MsgBox("Error", vbAbortRetryIgnore + vbDefaultButton3 + vbMsgBoxHelpButton)

' Abort/Retry/Ignore button with the Help button displayed and Help selected
resp = MsgBox("Error", vbAbortRetryIgnore + vbDefaultButton4 + vbMsgBoxHelpButton)

The following examples show some button selections and the title parameter being set:

' Retry/Cancel button with query warning as the icon and "Error" as the title
resp = MsgBox("An error occurred. Try again?", vbRetryCancel + vbQuestion, "Error")

' Ok button with critical icon and "System error" as the title
MsgBox "An error occurred", vbCritical, "System Error"

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

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

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

Default message in a VBA Msgbox

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

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

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

Содержание

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

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

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

Anatomy of an VBA Msgbox dialog box

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Sample message box

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

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

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

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

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

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

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

ok and cancel buttons in a message box

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

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

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

Excel VBA Msgbox - Abort Retry and Cancel buttons

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

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

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

Yes and No buttons in a message box

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

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

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

Excel VBA Message Box- Yes and No and Cancel

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

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

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

Retry and Cancel buttons

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

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

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

help button in the message box dialog box

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

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

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

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

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

by default, second button is selected

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

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

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

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

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

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

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

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

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

Excel VBA Msgbox - critical icon

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

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

Excel VBA Msgbox - critical icon YesNO

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

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

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

Excel VBA Msgbox - question icon

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

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

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

Excel VBA Msgbox - exclamation icon

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

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

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

Excel VBA Msgbox - information

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

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

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

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

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

Excel VBA Msgbox - title

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

Excel VBA Msgbox - prompt

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

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

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

Excel VBA Msgbox - vbnewline

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

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

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

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

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

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

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

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

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

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

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

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

Yes No prompt based on user selection

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

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

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

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

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

Skip to content

VBA MsgBox Excel Examples – 100+ Message Box Macros

Home » VBA » VBA MsgBox Excel Examples – 100+ Message Box Macros

  • Message Box(MsgBox) in Excel VBA Syntax

The MsgBox in VBA is a popup message box to display message in Excel VBA, Access VBA and other MS Office Applications. Excel VBA MsgBox shows Message Box using VBA Macro Programming with verity of Options and Types.

Message Box (MsgBox) VBA Macros explained with syntax. Use MsgBox in VBA to show vbYes, No and Cancel, vbexclamation, vbcritical, vbinformation message boxes and other advanced popup messages box models to display with icons and command buttons.

VBA MsgBox Function

VBA MsgBox is one of the most frequently used functions in VBA Application Development. We can use MsgBox Function in Microsoft Word, Excel, Access and PowerPoint VBA Programming. Excel VBA Message Box function displays a message, optional icon and selected set of command buttons in a dialog box. It waits for the user to click a button, and returns an Integer indicating the button which user clicked. Here is the syntax and different kinds of Message Boxes in VBA.

VBA MsgBox – Syntax:

Here is the syntax of VBA MsgBox Function. This is same in Excel, Word, Access, PowerPoint and VBScript.

MsgBox(prompt

[, buttons] [, title] [, helpfile, context])

VBA MsgBox in Excel VBA Syntax

Where

  1. Prompt: It Contains String expression displayed as the message in the dialog box. The Maximum length of Prompt is 1024 Characters. You can use carriage return Character,If prompt consists more than one line.
  2. buttons:It Contains Numeric value specifying the number and type of buttons to display.The default button value is 0.
  3. title:It Contains String expression displayed in the title bar of the dialog box.

VBA MsgBox in Excel VBA – Example Cases:

Here is a short video to show you VBA Message Box with different types of options:

Here are the different types of Message Boxes available in Excel VBA. You can click on each link to see the respective examples, Screenshots of output and explanation.

VBA MsgBox arguments

VBA MsgBox will take the following parameters: These options will change the appearance of the Message Box. You can change the model of the Message Box by combining different option of MsgBox Function.

  • MsgBox Prompt: This is the message text which you want to show/prompt
  • MsgBox Buttons Style: This is the type of message box which you want to show, like Yes No buttons with Information Icon
  • MsgBox Title: This is the title of the message box window
  • MsgBox Help File, and Context: These are the other optional parameters which we use in very rare

Here is the Hello World MsgBox Function example with Parameters.

MsgBox “Hello World!”, vbYesNo + vbInformation, “VBA Hello World Message Box Example Title”

The above MsgBox will show you Yes No Type message box with information icon and title.

VBA MessageBox Options and Uses

Let us see the different options and usage of Message Box Function. We can create verity of Message Boxes in VBA to handle different scenarios.

VBA MsgBox Styles

In Most cases we use vbYesNo Message Box and get the result to a variable. Let us see vbYesNo Syntax, arguments, parameters, yes no default buttons, yes no prompt and yes no examples. yes no if syntax helps us to decide based on the user input. We can check If yes no return, yes no answer.

MsgBox “This is the example Yes No Syntax”, vbYesNo

We can also create MsgBox with Yes No and Cancel values, and get the user yes, no or cancel responses. Instead of adding the strings in MsgBox Parameters. We can create variable string and pass as a string. We can use the variable for MsgBox Prompt or Title. Combining Yes No Button Types with different option, we can display yes no critical, yes no warning, yes no exclamation, yes no question type Msg Box. below arr syntax to change button caption, button labels, button names.

Here is the Example with Yes, No, Cancel and Exclamation Icon.

MsgBox “This is the example Yes No Cancel Syntax”, vbYesNoCancel + vbExclamation

We can use Userforms to create customized Message Boxes: MsgBox Without OK button, without buttons, no buttons to show prompt. We can use command buttons, radio buttons in UserForm. We can fortmat the text, Font Size, Font Color and set Bold text in MsgBox.

We can pass variable value or variable text create a string and use as MsgBox variable input for Prompt and Titles. Different buttons and icons of MsgBox are created for different purposes.

We can have multiple lines, access custom buttons, access new line, access carriage return, variable type, variable, error handling, on error goto, error message dialog box, display array, two lines, access multiple lines.

Excel VBA MsgBox Yes No Syntax

The following is the simple Example on VBA MsgBox Yes No Prompt Type. We can use this to receive the acceptance of user to certain criteria. And decide the further process.
MsgBox “This is the example Yes No Syntax”, vbYesNo

Check the below example, it will check if user clicked on Yes or No button. We can also show the Help when user pressing F1 button or Help button.

If MsgBox("Do you want to see know the current Time", vbYesNo) = vbYes Then
    MsgBox Format(Now(), "HH:MM:SS AMPM"), vbInformation, "Current Time"
End If

VBA MsgBox Yes No If

The following example on vba msgbox yes no if to show the different messages boxes based on the selected option. If then and exit sub syntax helps terminate the sub procedure based on the certain condition.

Sub sbKnowingUserInput()
intUserOption = MsgBox("Press Yes or No Button", vbYesNo)
If vbOption = 6 Then
 MsgBox "You Pressed YES Option"
ElseIf vbOption = 7 Then
    MsgBox "You Pressed NO Option"
Else
    MsgBox "Nothing!"
End If

End Sub

VBA Message Box New line,carriage return, two lines, multiple line

We can use vbCr to split the message box text into a new line and add carriage return to make into two lines. We can use & vbCr to split the message into multiple lines.
MsgBox “Hello, This is Line ONE” & vbCr & “This is Line TWO”

VBA MsgBox Yes No Cancel Return

The below example on vba msgbox yes no cancel return to access the response of MsgBox. This will help us to access,store and input the msgbox response or string in variable value. We can use this variable text in the further programming.

Dim msgValue 
msgValue = MsgBox("Hello, Are you a graduate? Choos:" _
& vbCr & "Yes: if you are a graduate" _
& vbCr & "Yes: if you are Not a graduate" _
& vbCr & "Yes: if you are Not Intrested" _
, vbYesNoCancel + vbQuestion)

If msgValue = vbYes Then
    MsgBox "You are eligible for applying for this Job"
ElseIf msgValue = vbNo Then
    MsgBox "You are NOT eligible for applying for this Job"
ElseIf msgValue = vbCancel Then
    MsgBox "No Problems, We will find suitable job for you"
End If

VBA If Then MsgBox and Exit Sub

Some times we may want to ask user to continue further, other wise skip the execution of next program. The below example on VBA if then msgbox and exit sub will help you to do this:

Sub sbPressYesToExitSub()
If MsgBox("Would you like to continue...?", vbQuestion + vbYesNo) <> vbYes Then
    Exit Sub
End If

'The below statements will not be executed when your press Yes button.
'You can write the next programming steps here... This will execute if user selects No in the above prompt.

MsgBox "You have not pressed Yes button"
End Sub

VBA On Error GoTo Message Box for Error Handling

MsgBox is also useful in error handling. We can tell VBA error message on error. Or we can go to a label and show message box with error number and description. The below code will execute the code and show the error number and description if there is any run-time error.

Sub sbShowing_Error_MessageBox()
On Erro GoTo ErrorHanMsg1
'Your code goes here....

Exit Sub
'This comes before End Sub or End Function Statement
ErrorHanMsg1:
MsgBox Err.Number & vbCr & Err.Description

End Sub

VBA MsgBox Styles

Here are the list of styles and models of Message Box Function in VBA. We combine different options to display a message box with desired options.

  • vbOKOnly: Displays the message box with OK button
  • vbOKCancel: This option will show you two buttons, OK and Cancel button to the user.
  • vbAbortRetryIgnore: MsgBox with three buttons, Abort, Retry and Ignore buttons.
  • vbYesNoCancelShows 3 buttons: Yes, No and Cancel.
  • vbYesNo: Shows both Yes, No buttons
  • vbRetryCancel: Helps to display Retry and Cancel buttons
  • vbCritical: Adds Critical Warning Icon to message box
  • vbQuestion: Question mark Icon will be added to message box
  • vbExclamation: Exclamation mark will be added to the MsgBox
  • vbInformation: Information symbol can show on message box
  • vbDefaultButton1: To set the focus on the first button
  • vbDefaultButton2: You can set the focus on the second button
  • vbDefaultButton3: To set the focus on the third button
  • vbDefaultButton4: You can set the focus on the fourth button
  • vbApplicationModal: Close MsgBox to access to Current applications
  • vbSystemModal: Close MsgBox to access to All applications
  • vbMsgBoxHelpButton:Shows Help Button on the message box
  • VbMsgBoxSetForeground:Set MsgBox Foreground
  • vbMsgBoxRight: Text aligned to right.
  • vbMsgBoxRtlReading: RTL support
  • Custom Message Box in Excel VBA: Using UserForms.
  • Message Box Constants in Excel VBA
  • Message Box Return Constants and Enumerations in Excel VBA

VBA MsgBox:vbOKOnly

Please find the following code and output. It will Display OK button only. When we click OK button, It will return value 1 as a output.

Code:
Sub MessageBox_vbOKOnly()

    'Variable Declaration
    Dim OutPut As Integer

    'Example of vbOKOnly
    OutPut = MsgBox("Thanks for visiting Analysistabs!", vbOKOnly, "Example of vbOKOnly")

End Sub
Output:

Excel VBA Message Box

Top

VBA MsgBox: vbOKCancel MessageBox

Please find the following code and output. It will Display OK and Cancel buttons. When we click OK button, It will return value 1 as a output.And When we click Cancel button, It will return value 2 as a output.

Code:
Sub MessageBox_vbOKCancel()

    'Variable Declaration
    Dim OutPut As Integer

    'Example of vbOKCancel
    OutPut = MsgBox("You are VBA Expert, is it True?", vbOKCancel, "Example of vbOKCancel")

    If OutPut = 1 Then
        'Output = 1(Ok)
        MsgBox "Grate! You are VBA Expert, You can learn Advanced Our VBA!", , "Ok - 1"
    Else
        'Output = 2(Cancel)
        MsgBox "You can Star Learning from Basics!", , "Cancel - 2"
    End If

End Sub
Output:

vbOKCancel Excel VBA Message Box

Top

VBA MsgBox: vbAbortRetryIgnore

Please find the following code and output. It will Display Abort, Retry, and Ignore buttons. When we click Abort button, It will return value 3 as a output. When we click Retry button, It will return value 4 as a output.And When we click Ignore button, It will return value 5 as a output.

Code:
Sub MessageBox_vbAbortRetryIgnore()

    'Variable Declaration
    Dim OutPut As Integer

    'Example of vbAbortRetryIgnore
    OutPut = MsgBox("The Connection has failed. Do you want to Continue?", vbAbortRetryIgnore, "Example of vbAbortRetryIgnore")

    If OutPut = 3 Then
        'Output = 1(Abort)
        MsgBox "Abort!", , "Abort - 3"
    ElseIf OutPut = 4 Then
        'Output = 4(Retry)
        MsgBox "Retry!", , "Retry - 4"
    Else
        'Output = 5(Ignore)
        MsgBox "Ignore!", , "Ignore - 5"
    End If

End Sub
Output:

vbAbortRetryIgnore Excel VBA MsgBox

Top

VBA MsgBox in Excel: vbYesNoCancel MessageBox

Please find the following code and output. It will Display Yes, No, and Cancel buttons. When we click Yes button, It will return value 6 as a output. When we click No button, It will return value 7 as a output.And When we click Cancel button, It will return value 2 as a output.

Code:
Sub MessageBox_vbYesNoCancel()

    'Variable Declaration
    Dim OutPut As Integer

    'Example of vbYesNoCancel
    OutPut = MsgBox("File already exists. Do you want to replace?", vbYesNoCancel, "Example of vbYesNoCancel")

    If OutPut = 6 Then
        'Output = 6(Yes)
        MsgBox "Yes!", vbInformation, "Yes - 6"
    ElseIf OutPut = 7 Then
        'Output = 7(No)
        MsgBox "No!", vbInformation, "No - 7"
    Else
        'Output = 2(Cancel)
        MsgBox "Cancel!", vbInformation, "Cancel - 2"
    End If

End Sub
Output:

VBA MsgBox in Excel VBA

Top

VBA MsgBox: vbYesNo

Please find the following code and output.It will display Display Yes and No buttons. When we click Yes button, It will return value 6 as a output.And, When we click No button, It will return value 7 as a output.

Code:
Sub MessageBox_vbYesNo()

    'Variable Declaration
    Dim OutPut As Integer

    'Example of vbYesNo
    OutPut = MsgBox("Do you want to replace the existing file?", vbYesNo, "Example of vbYesNo")

    If OutPut = 6 Then
        'Output = 6(Yes)
        MsgBox "Yes! Replace the file", vbInformation, "Yes - 6"
    Else
        'Output = 7(No)
        MsgBox "No! Don't replace the file", , "No - 7"
    End If

End Sub
Output:

vbYesNo MsgBox VBA

Top

MsgBox in Excel VBA: vbRetryCancel MessageBox

Please find the following code and output. It will Display Retry and Cancel buttons.When we click Retry button, It will return value 4 as a output.And, When we click Cancel button, It will return value 2 as a output.

Code:
Sub MessageBox_vbRetryCancel()

    'Variable Declaration
    Dim OutPut As Integer

    'MsgBox VBA Example of vbRetryCancel
    OutPut = MsgBox("Close the File.Try Again?", vbRetryCancel + vbDefaultButton2, "Example of vbRetryCancel")

    If OutPut = 4 Then
        'Output = 4(Retry)
        MsgBox "Retry!", , "Retry - 4"
    Else
        'Output = 2(Cancel)
        MsgBox "Cancel It!", , "Cancel - 2"
    End If

End Sub
Output:

VBA MsgBox in Excel VBA

Top

VBA MsgBox: vbCritical

Please find the following code and output. When we click Ok button, It will return value 1 as a output. And, It will display critical Message Icon.

Code:
Sub MessageBox_vbCritical()

    'Variable Declaration
    Dim OutPut As Integer

    'Example of vbCritical
    OutPut = MsgBox("Please enter valid Number!", vbCritical, "Example of vbCritical")

End Sub
Output:

VBA MsgBox in Excel VBA

Top

VBA MsgBox: vbQuestion

Please find the following code and output.When we click Ok button, It will return value 1 as a output. And, It will display Warning Query icon.

Code:
Sub MessageBox_vbQuestion()

    'Variable Declaration
    Dim OutPut As Integer

    'Example of vbQuestion
    OutPut = MsgBox("Are you fresher?", vbQuestion, "Example of vbQuestion")

End Sub
Output:

VBA MsgBox in Excel VBA

Top

VBA MsgBox: vbExclamation

Please find the following code and output.When we click Ok button, It will return value 1 as a output. And, It will display Warning Message icon.

Code:
Sub MessageBox_vbExclamation()

    'Variable Declaration
    Dim OutPut As Integer

    'Example of vbExclamation
    OutPut = MsgBox("Input Data is not valid!", vbExclamation, "Example of vbExclamation")

End Sub
Output:

VBA MsgBox in Excel VBA

Top

VBA MsgBox: vbInformation

Please find the following code and output.When we click Ok button, It will return value 1 as a output. And, It will display Information Message icon.

Code:
Sub MessageBox_vbInformation()

    'Variable Declaration
    Dim OutPut As Integer

    'Example of vbInformation
    OutPut = MsgBox("Succesessfully Completed the Task.", vbInformation, "Example of vbInformation")

End Sub
Output:

VBA MsgBox in Excel VBA

Top

VBA MsgBox: vbDefaultButton1

Please find the following code and output. By Default it will focus on first (Retry) Button. When we press enter it will result the value of Retry button as 4.

Code:
Sub MessageBox_vbDefaultButton1()

    'Variable Declaration
    Dim OutPut As Integer

    'Example of vbDefaultButton1
    OutPut = MsgBox("Close the File.Try Again?", vbRetryCancel + vbDefaultButton1, "Example of vbDefaultButton1")

End Sub
Output:

VBA MsgBox in Excel VBA

Top

VBA MsgBox: vbDefaultButton2

Please find the following code and output.By Default it will focus on Second(Cancel) Button. When we press enter it will result the value of Retry button as 2.

Code:
Sub MessageBox_vbDefaultButton2()

    'Variable Declaration
    Dim OutPut As Integer

    'Example of vbDefaultButton2
    OutPut = MsgBox("Close the File.Try Again?", vbRetryCancel + vbDefaultButton2, "Example of vbDefaultButton2")

End Sub
Output:

VBA MsgBox in Excel VBA

Top

VBA MsgBox: vbDefaultButton3

Please find the following code and output.By Default it will focus on Third(Cancel) Button. When we press enter it will result the value of Retry button as 2.

Code:
Sub MessageBox_vbDefaultButton3()

    'Variable Declaration
    Dim OutPut As Integer

    'Example of vbDefaultButton2
    OutPut = MsgBox("Close the File.Try Again?", vbYesNoCancel + vbDefaultButton3, "Example of vbDefaultButton3")

End Sub
Output:

VBA MsgBox in Excel VBA

Top

VBA MsgBox: vbApplicationModal

Please find the following code and output.The user must respond to the message box before continuing work in the current application.

Code:
Sub MessageBox_vbApplicationModal()

    'Variable Declaration
    Dim OutPut As Integer

    'Example of vbApplicationModal
    OutPut = MsgBox("Thanks for visiting Analysistabs!", vbApplicationModal, "Example of vbApplicationModal")

End Sub
Output:

VBA MsgBox in Excel VBA

Top

VBA MsgBox: vbSystemModal

Please find the following code and output.All applications are suspended until the user responds to the message box.

Code:
Sub MessageBox_vbSystemModal()

    'Variable Declaration
    Dim OutPut As Integer

    'Example of vbSystemModal
    OutPut = MsgBox("Thanks for visiting Analysistabs!", vbSystemModal, "Example of vbSystemModal")

End Sub
Output:

VBA MsgBox in Excel VBA

Top

VBA MsgBox: vbMsgBoxHelpButton

Please find the following code and output.Adds Help button to the message box.

Code:
Sub MessageBox_vbMsgBoxHelpButton()

    'Variable Declaration
    Dim OutPut As Integer

    'Example of vbMsgBoxHelpButton
    OutPut = MsgBox("Thanks for visiting Analysistabs!", vbMsgBoxHelpButton, "Example of vbMsgBoxHelpButton")

End Sub
Output:

VBA MsgBox in Excel VBA

Top

VBA MsgBox: VbMsgBoxSetForeground

Please find the following code and output.Specifies the message box window as the foreground window.

Code:
Sub MessageBox_VbMsgBoxSetForeground()

    'Variable Declaration
    Dim OutPut As Integer

    'Example of VbMsgBoxSetForeground
    OutPut = MsgBox("Thanks for visiting Analysistabs!", vbMsgBoxSetForeground, "Example of VbMsgBoxSetForeground")

End Sub
Output:

VBA MsgBox in Excel VBA

Top

VBA MsgBox: vbMsgBoxRight

Please find the following code and output.Here text is right aligned.

Code:
Sub MessageBox_vbMsgBoxRight()

    'Variable Declaration
    Dim OutPut As Integer

    'Example of vbMsgBoxRight
    OutPut = MsgBox("Input Data is not valid!", vbMsgBoxRight, "Example of vbMsgBoxRight")

End Sub
Output:

VBA MsgBox in Excel VBA

Top

VBA MsgBox: vbMsgBoxRtlReading

Please find the following code and output.It Specifies text should appear as right-to-left reading on Hebrew and Arabic systems.

Code:
Sub MessageBox_vbMsgBoxRtlReading()

    'Variable Declaration
    Dim OutPut As Integer

    'Example of vbMsgBoxRtlReading
    OutPut = MsgBox("Thanks for visiting Analysistabs!", vbMsgBoxRtlReading, "Example of vbMsgBoxRtlReading")

End Sub
Output:

VBA MsgBox in Excel VBA

Instructions:
  1. Open an excel workbook
  2. Press Alt+F11 to open VBA Editor
  3. Double click on ThisWorkbook from Project Explorer
  4. Copy the above code and Paste in the code window
  5. Press F5
  6. You should see the above output

Custom Message Box in Excel VBA:

What if your requirement is not achievable with the available types of MessageBox. You Can create your own MessageBox using Forms in Excel VBA. You can design your own custom MessageBox using Form Controls.
Here is the example Custom MessageBox.
Custom Msgbox in Excel VBA

Top

MessageBox Constants in Excel VBA:

Please find the following table for button argument values:

Constant Value Description
vbOKOnly 0 It Display’s OK button only.
vbOKCancel 1 It Display’s OK and Cancel buttons.
vbAbortRetryIgnore 2 It Display’s Abort, Retry, and Ignore buttons.
vbYesNoCancel 3 It Display’s Yes, No, and Cancel buttons.
vbYesNo 4 It Display’s Yes and No buttons.
vbRetryCancel 5 It Display’s Retry and Cancel buttons.
vbCritical 16 It Display’s Critical Message icon.
vbQuestion 32 It Display’s Warning Query icon.
vbExclamation 48 It Display’s Warning Message icon.
vbInformation 64 It Display’s Information Message icon.
vbDefaultButton1 0 Here first button is default.
vbDefaultButton2 256 Here second button is default.
vbDefaultButton3 512 Here third button is default.
vbDefaultButton4 768 Here fourth button is default.
vbApplicationModal 0 Application modal. The user must respond to the message box before continuing work in the current application.
vbSystemModal 4096 System modal. In this case all applications are suspended until the user responds to the message box.
vbMsgBoxHelpButton 16384 Adds Help button to the message box.
VbMsgBoxSetForeground 65536 Specifies the message box window as the foreground window.
vbMsgBoxRight 524288 Text is right aligned.
vbMsgBoxRtlReading 1048576 Specifies text should appear as right-to-left reading on Hebrew and Arabic systems.

Top

Message Box Return Constants and Enumerations in Excel VBA:

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

Top

Recommended Resource

  • VBA Open File DialogBox Macros
  • VBA InputBox Macros
  • VBA ComboBox
  • VBA ListBox
  • VBA CheckBox
  • VBA CommandButton
  • VBA TextBox
  • VBA Userform CheckBox
  • VBA Userform ComboBox
  • VBA Userform CommandButton
  • VBA Userform Image
  • VBA Userform Label
  • VBA Userform ListBox
  • VBA Userform OptionButton
  • VBA Userform TextBox
Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates

Related Posts

  • VBA MsgBox Function
    • VBA MsgBox – Syntax:
    • VBA MsgBox in Excel VBA – Example Cases:
    • VBA MsgBox arguments
  • VBA MessageBox Options and Uses
      • VBA MsgBox Styles
  • Excel VBA MsgBox Yes No Syntax
  • VBA MsgBox Yes No If
  • VBA Message Box New line,carriage return, two lines, multiple line
    • VBA MsgBox Yes No Cancel Return
  • VBA If Then MsgBox and Exit Sub
  • VBA On Error GoTo Message Box for Error Handling
  • VBA MsgBox Styles
  • VBA MsgBox:vbOKOnly
  • VBA MsgBox: vbOKCancel MessageBox
  • VBA MsgBox: vbAbortRetryIgnore
    • VBA MsgBox in Excel: vbYesNoCancel MessageBox
  • VBA MsgBox: vbYesNo
  • MsgBox in Excel VBA: vbRetryCancel MessageBox
  • VBA MsgBox: vbCritical
  • VBA MsgBox: vbQuestion
  • VBA MsgBox: vbExclamation
  • VBA MsgBox: vbInformation
  • VBA MsgBox: vbDefaultButton1
  • VBA MsgBox: vbDefaultButton2
  • VBA MsgBox: vbDefaultButton3
  • VBA MsgBox: vbApplicationModal
  • VBA MsgBox: vbSystemModal
  • VBA MsgBox: vbMsgBoxHelpButton
  • VBA MsgBox: VbMsgBoxSetForeground
  • VBA MsgBox: vbMsgBoxRight
  • VBA MsgBox: vbMsgBoxRtlReading
  • Custom Message Box in Excel VBA:
  • MessageBox Constants in Excel VBA:
    • Message Box Return Constants and Enumerations in Excel VBA:
      • Recommended Resource

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

19 Comments

  1. Shady Mohsen
    January 21, 2014 at 11:02 PM — Reply

    Thanks friend. It helped me a lot.I appreciate your efforts on creating useful VBA codes.

  2. ramana
    January 31, 2015 at 11:57 PM — Reply

    nice post..
    is there any suggestion how to display message box from the statement ‘For – Next’ , but the message itself does not appear repeatedly based on that ‘For-Next’ values?

  3. PNRao
    February 3, 2015 at 10:14 PM — Reply

    Hi Ramana,
    You can use a Boolean variable to do this:

    Sub ShowMsgOnceInForLoop()
    Dim msgFlag As Boolean
    msgFlag = False
    
    For iCntr = 1 To 100
    
    If msgFlag = False Then
    MsgBox "This is MSGBox"
    msgFlag = True
    End If
    
    Next
    
    End Sub
    

    Instead of this flag, you may use any other condition when you want to show the Message box.

    Thanks-PNRao!

  4. Dilip
    March 4, 2015 at 1:46 PM — Reply

    i want to replace MsgBox appearing for Data Validation – Input & Error Message. I want to skip Help Button in Excel Default Message and add our own Message Title. Is there any way to do this ? Pl. provide VBA code only. Don’t waste your time in explaining how this can be done through Ribbon Menu pl. I will be highly obliged if i get the solution asap.If you require further information pl. let me know asap.

  5. PNRao
    March 7, 2015 at 7:34 PM — Reply

    Hi Dilip,

    Please see the below VBA example code for Data validation and Custom mesagebox.

    Sub sbCustomDatavalidation()
        With Range("A1:A5").Validation
            .Delete
            .Add Type:=xlValidateWholeNumber, AlertStyle:=xlValidAlertStop, _
            Operator:=xlBetween, Formula1:="1", Formula2:="5"
            .IgnoreBlank = True
            .InCellDropdown = True
            .InputTitle = "Enter #Items"
            .InputMessage = "Enter an value between 1 to 5"
            
            .ErrorTitle = "My Message Box title"
            .ErrorMessage = "My Message Box Description"
            .ShowInput = True
            .ShowError = True
        End With
    End Sub
    

    Thanks-PNRao!

  6. Paul
    April 14, 2015 at 11:43 PM — Reply

    Hey Valli, Great article!

    I was wondering … I’d like a box to pop up for one second (or other time period), then dismiss itself without user interaction.
    Can msgbox be made to do this, or is there a different command that could do this?
    Thanks

  7. pratyush
    December 26, 2015 at 9:10 PM — Reply

    I learned so many things from all above.Thanks and please stay-Tuned.
    All the VBA beginners like me are refering all these and its very helpful.

    Thanks Again. .

  8. Csaba
    March 2, 2016 at 6:01 PM — Reply

    How I can stop the “X” button from the upper right corner to close the msgbox, practically force the user to respond with assigned buttons. Something similar with UserForm_QueryClose(Cancel As Integer, CloseMode As Integer), cancel = false, and post a message.

  9. Stephen Nzai
    September 6, 2016 at 7:40 PM — Reply

    Can someone tell me how to put the displaced value on a message box on a cell. Lets say the message box displays integer 5, how do I get it on a cell without typing it?

  10. sambit
    September 15, 2016 at 10:56 AM — Reply

    i need VBA code so that i can get an alert when a cell in excel exceeds certain specified number which is automatically populated by the server

  11. Bob
    November 8, 2016 at 2:25 AM — Reply

    Funny everyone illustrates how to add a help button, but no one will attempt to demonstrate how to get the help button to display help. The help button example above works great and pops up an empty help file. However if you add the next parameter, the help file path, vbscript complains – “Invalid procedure call or arguments: MsgBox”. The “.chm” file I tested with works great if you click on the file directly. Does this mean that not all .chm help files are windows compatible or is MsgBox broken.

  12. ParismaX
    February 14, 2017 at 6:03 PM — Reply

    I was wondering if I could make a message box display the user’s name.
    I know it is possible to do this but how would I go about it?

  13. Gregory Feeney
    May 27, 2017 at 8:29 PM — Reply

    Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    Dim MyValue As String
    ‘Set MyValue to whatever you want
    MyValue = 1

    ‘Set the Range to what ever cell you want to monitor changes

    If Range(“A1”) > MyValue Then
    MsgBox “Alert Box Appears”
    End If

    End Sub

  14. Sub DisplayUserName()
    msgBox “The User Name is: ” & Environ(“UserName”),vbInformation,”User Name”
    End Sub

  15. Colin Riddington
    June 17, 2017 at 3:30 AM — Reply

    You can use the Environ function to get the logged on user name

    e.g. MsgBox “Hello ” & Environ(“UserName”),vbExclamation,”MsgBox Title”

    However the user name may not give the person’s forename.
    Otherwise use DLookup to find the forename in a table.
    e.g. If you have a table tblUsers with logged user info including a field called Forename and UserID stored as a string strUserID, you could use DLookup something like this:

    MsgBox “Hello ” & DLookup(“Forename”,”tblUsers”,”UserID”= ‘” & strUserID & “‘”),vbExclamation,”MsgBox Title”

  16. Ariful Romadhon
    August 5, 2017 at 3:54 PM — Reply

    Could you help me please?
    I want to make message box for validating surveys.
    the message box contain the message because error of stuffing

    I want my message box keep showing, so i can click the sheets which contain error of stuffing without closing the message box.

    So, the message box will guide me to fix the error in that sheets

    This is my previous code:

    Dim error As String
    error = ”

    If (vehicle = True) And (gasoline_month = 0) Then
    error = error & “- the expenditure of gasoline should not be empty” & Chr(10)
    End If

    If error = “” Then msgbox “clean”, vbInformation Else MsgBox error, vbCritical
    End Sub

    Thank you, I hope anyone can help me,,
    (sorry for my bad english)

  17. rathy
    August 12, 2017 at 10:23 PM — Reply

    Dim msgValue
    msgValue = MsgBox(“Hello, Are you a graduate? Choos:” _
    & vbCr & “Yes: if you are a graduate” _
    & vbCr & “Yes: if you are Not a graduate” _
    & vbCr & “Yes: if you are Not Intrested” _
    , vbYesNoCancel + vbQuestion)

    I think the above incorrect right, it should be

    Dim msgValue
    msgValue = MsgBox(“Hello, Are you a graduate? Choos:” _
    & vbCr & “Yes: if you are a graduate” _
    & vbCr & “No: if you are Not a graduate” _
    & vbCr & “Cancel: if you are Not Intrested” _
    , vbYesNoCancel + vbQuestion)

    .

  18. Mike
    September 4, 2017 at 7:26 PM — Reply

    Very helpful. Perfect Macros. Thanks you.

  19. ajay
    October 10, 2020 at 8:20 PM — Reply

    can give msg box button a person name.. just like yes no or ok cancel

    thanks

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

VBA Projects With Source Code

3 Realtime VBA Projects
with Source Code!

Take Your Projects To The Next Level By Exploring Our Professional Projects

Go to Top

Like this post? Please share to your friends:
  • Vba for excel instr
  • Vba import word to excel
  • Vba for excel insert row
  • Vba hyperlink excel cell
  • Vba for excel inputbox