REAL-TIME

VBA Projects

Full Access with Source Code

  • Designed and Developed by PNRao

  • Full Access with VBA Source Code

  • Well Commented Codes Lines

  • Creative and Professional Design

120+ PROFESSIONAL

Project Management Templates

120+ PM Templates Includes:
  • 50+ Excel Templates

  • 50+ PowerPoint Templates

  • 25+ Word Templates

Effortlessly Manage Your Projects

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

Share Post

VBA MsgBox examples for every kind of pop-up message box you can build in Excel, Word, Access, PowerPoint and VBScript. Each example below is copy-and-run, with the constant, its value, and what the user sees.

The MsgBox function displays a message with an optional icon and a chosen set of buttons, waits for the user to click one, and returns an integer telling you which. That return value is what makes it useful — it lets a macro branch on a decision the user just made.

VBA MsgBox syntax

The syntax is identical in Excel, Word, Access, PowerPoint and VBScript. Only prompt is required.

MsgBox(prompt [, buttons] [, title] [, helpfile, context])
Argument Required What it does
prompt Yes The message text. Maximum 1,024 characters. Use vbCr to break it across lines.
buttons No A number setting which buttons and which icon appear. Default is 0. Add constants together to combine them.
title No The text in the title bar. Defaults to the application name.
helpfile, context No Help file and topic, used only when you show a Help button. Rarely needed.

A message box with all three common arguments:

MsgBox "Hello World!", vbYesNo + vbInformation, "Hello World Example"

That shows Yes and No buttons with an information icon and a custom title. The + is how you combine a button constant with an icon constant.

VBA MsgBox syntax showing the prompt, buttons, title, helpfile and context arguments

VBA MsgBox constants: the complete reference

Everything you can pass in the buttons argument. Pick one from the button group, optionally add one icon, and optionally add a default-button constant.

Button constants

Constant Value Buttons shown
vbOKOnly 0 OK button only
vbOKCancel 1 OK and Cancel
vbAbortRetryIgnore 2 Abort, Retry and Ignore
vbYesNoCancel 3 Yes, No and Cancel
vbYesNo 4 Yes and No
vbRetryCancel 5 Retry and Cancel

Icon constants

Constant Value Icon shown
vbCritical 16 Critical message icon — a red cross
vbQuestion 32 Query icon — a question mark
vbExclamation 48 Warning icon — an exclamation mark
vbInformation 64 Information icon — a blue i

Default button constants

Constant Value Effect
vbDefaultButton1 0 First button has focus
vbDefaultButton2 256 Second button has focus
vbDefaultButton3 512 Third button has focus
vbDefaultButton4 768 Fourth button has focus

Modality and display constants

Constant Value Effect
vbApplicationModal 0 User must respond before continuing in the current application
vbSystemModal 4096 All applications are suspended until the user responds
vbMsgBoxHelpButton 16384 Adds a Help button
VbMsgBoxSetForeground 65536 Makes the message box the foreground window
vbMsgBoxRight 524288 Text is right aligned
vbMsgBoxRtlReading 1048576 Right-to-left reading for Hebrew and Arabic systems

VBA MsgBox return values

Whichever button the user clicks, MsgBox returns a number. Test against the named constant rather than the number — vbYes is clearer than 6 and cannot be mistyped.

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

Assign the result to capture it

To read the return value you must use parentheses and assign the result: x = MsgBox("Text", vbYesNo). Written without parentheses as a statement, MsgBox "Text", vbYesNo, the return value is discarded.

VBA MsgBox Yes No

The most common use of a message box is asking a yes-or-no question and branching on the answer.

Sub MsgBox_YesNo()

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

End Sub

MsgBox Yes No with If Then Else

Store the result in a variable when you need more than two branches, or when you want to use the answer later in the procedure.

Sub MsgBox_YesNo_IfThen()

    Dim userChoice As Integer

    userChoice = MsgBox("Press Yes or No", vbYesNo, "Your choice")

    If userChoice = vbYes Then
        MsgBox "You pressed Yes"
    ElseIf userChoice = vbNo Then
        MsgBox "You pressed No"
    End If

End Sub

MsgBox Yes No Cancel

Three buttons give you three branches. Cancel is the natural place to abandon whatever the macro was about to do.

Sub MsgBox_YesNoCancel()

    Dim answer As Integer

    answer = MsgBox("File already exists. Replace it?", _
                    vbYesNoCancel + vbQuestion, "Confirm replace")

    If answer = vbYes Then
        MsgBox "Replacing the file", vbInformation
    ElseIf answer = vbNo Then
        MsgBox "Keeping the existing file", vbInformation
    Else
        MsgBox "Cancelled", vbInformation
    End If

End Sub

MsgBox Yes No with Exit Sub

A confirmation prompt that stops the macro when the user declines. Note the <> vbYes test — it treats Cancel and the window’s close button the same as No, which is usually what you want.

Sub MsgBox_ConfirmOrExit()

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

    ' Everything below runs only if the user pressed Yes
    MsgBox "Continuing...", vbInformation

End Sub

VBA MsgBox new line, carriage return and multiple lines

Use vbCr — or vbNewLine, which does the same thing — joined with & to split a message across lines.

MsgBox "This is line one" & vbCr & "This is line two"

For a longer message, break the VBA statement itself with a line-continuation underscore so the code stays readable:

Sub MsgBox_MultipleLines()

    Dim answer As Integer

    answer = MsgBox("Are you a graduate?" _
        & vbCr & vbCr _
        & "Yes    - I am a graduate" _
        & vbCr & "No     - I am not a graduate" _
        & vbCr & "Cancel - I would rather not say" _
        , vbYesNoCancel + vbQuestion, "Eligibility")

    If answer = vbYes Then
        MsgBox "You are eligible to apply"
    ElseIf answer = vbNo Then
        MsgBox "You are not eligible to apply"
    Else
        MsgBox "No problem — we will find something suitable"
    End If

End Sub

vbCr, vbLf, vbCrLf and vbNewLine

In a message box all four produce a line break, so vbCr is fine. The distinction matters when you write to a text file or a cell: vbCrLf is the Windows line ending, vbLf the Unix one, and vbNewLine resolves to whichever suits the platform.

VBA MsgBox button examples

vbOKOnly

A single OK button. This is the default, so MsgBox "Text" and MsgBox "Text", vbOKOnly are identical. Returns 1.

Sub MessageBox_vbOKOnly()

    Dim result As Integer
    result = MsgBox("Thanks for visiting Analysistabs!", vbOKOnly, "Example of vbOKOnly")

End Sub

VBA MsgBox vbOKOnly example showing a single OK button

vbOKCancel

OK and Cancel. Returns 1 for OK, 2 for Cancel.

Sub MessageBox_vbOKCancel()

    Dim result As Integer
    result = MsgBox("Are you a VBA expert?", vbOKCancel, "Example of vbOKCancel")

    If result = vbOK Then
        MsgBox "Great! Try the advanced tutorials.", , "OK - 1"
    Else
        MsgBox "Start learning from the basics.", , "Cancel - 2"
    End If

End Sub

VBA MsgBox vbOKCancel example showing OK and Cancel buttons

vbAbortRetryIgnore

Abort, Retry and Ignore. Returns 3, 4 or 5. Useful when an operation can be retried, such as a failed connection.

Sub MessageBox_vbAbortRetryIgnore()

    Dim result As Integer
    result = MsgBox("The connection failed. Continue?", _
                    vbAbortRetryIgnore, "Example of vbAbortRetryIgnore")

    If result = vbAbort Then
        MsgBox "Abort", , "Abort - 3"
    ElseIf result = vbRetry Then
        MsgBox "Retry", , "Retry - 4"
    Else
        MsgBox "Ignore", , "Ignore - 5"
    End If

End Sub

VBA MsgBox vbAbortRetryIgnore example showing Abort, Retry and Ignore buttons

vbYesNoCancel

Yes, No and Cancel. Returns 6, 7 or 2.

Sub MessageBox_vbYesNoCancel()

    Dim result As Integer
    result = MsgBox("File already exists. Replace it?", _
                    vbYesNoCancel, "Example of vbYesNoCancel")

    If result = vbYes Then
        MsgBox "Yes", vbInformation, "Yes - 6"
    ElseIf result = vbNo Then
        MsgBox "No", vbInformation, "No - 7"
    Else
        MsgBox "Cancel", vbInformation, "Cancel - 2"
    End If

End Sub

VBA MsgBox vbYesNoCancel example showing Yes, No and Cancel buttons

vbYesNo

Yes and No. Returns 6 or 7. Note there is no Cancel, so the user cannot dismiss it with the close button — the X is disabled.

Sub MessageBox_vbYesNo()

    Dim result As Integer
    result = MsgBox("Replace the existing file?", vbYesNo, "Example of vbYesNo")

    If result = vbYes Then
        MsgBox "Yes — replacing the file", vbInformation, "Yes - 6"
    Else
        MsgBox "No — keeping the file", , "No - 7"
    End If

End Sub

VBA MsgBox vbYesNo example showing Yes and No buttons

vbRetryCancel

Retry and Cancel. Returns 4 or 2.

Sub MessageBox_vbRetryCancel()

    Dim result As Integer
    result = MsgBox("Close the file and try again?", _
                    vbRetryCancel + vbDefaultButton2, "Example of vbRetryCancel")

    If result = vbRetry Then
        MsgBox "Retry", , "Retry - 4"
    Else
        MsgBox "Cancel", , "Cancel - 2"
    End If

End Sub

VBA MsgBox vbRetryCancel example showing Retry and Cancel buttons

VBA MsgBox icon examples

vbCritical

Value 16. Shows the critical-error icon, a white cross on red. Use it when something has actually failed, not for warnings.

Sub MessageBox_vbCritical()

    MsgBox "Please enter a valid number.", vbCritical, "Example of vbCritical"

End Sub

VBA MsgBox vbCritical example showing the critical error icon

vbQuestion

Value 32. Shows a question mark. Pair it with vbYesNo when you are genuinely asking something.

Sub MessageBox_vbQuestion()

    MsgBox "Are you new to VBA?", vbQuestion, "Example of vbQuestion"

End Sub

VBA MsgBox vbQuestion example showing the question mark icon

vbExclamation

Value 48. Shows a warning triangle. The right choice when the user can still proceed but should think first.

Sub MessageBox_vbExclamation()

    MsgBox "The input data is not valid.", vbExclamation, "Example of vbExclamation"

End Sub

VBA MsgBox vbExclamation example showing the warning icon

vbInformation

Value 64. Shows a blue information icon. The default choice for confirming that something finished successfully.

Sub MessageBox_vbInformation()

    MsgBox "Task completed successfully.", vbInformation, "Example of vbInformation"

End Sub

VBA MsgBox vbInformation example showing the information icon

VBA MsgBox default button

The default button is the one that already has focus, so pressing Enter selects it. Use it to make the safe choice the easy one.

vbDefaultButton1

Value 0. Focus on the first button — the default behaviour.

MsgBox "Close the file and try again?", vbRetryCancel + vbDefaultButton1, "vbDefaultButton1"

VBA MsgBox vbDefaultButton1 example with focus on the first button

vbDefaultButton2

Value 256. Focus on the second button.

MsgBox "Close the file and try again?", vbRetryCancel + vbDefaultButton2, "vbDefaultButton2"

VBA MsgBox vbDefaultButton2 example with focus on the second button

vbDefaultButton3

Value 512. Focus on the third button.

MsgBox "Close the file and try again?", vbYesNoCancel + vbDefaultButton3, "vbDefaultButton3"

VBA MsgBox vbDefaultButton3 example with focus on the third button

vbDefaultButton4

Value 768. Focus on the fourth button. In practice this only applies when a Help button is present, since no standard button set has four buttons.

MsgBox "Need help with this step?", vbYesNoCancel + vbMsgBoxHelpButton + vbDefaultButton4, "vbDefaultButton4"

VBA MsgBox modality and display options

vbApplicationModal

Value 0, the default. The user must respond before continuing in the current application, but other applications stay usable.

MsgBox "Thanks for visiting Analysistabs!", vbApplicationModal, "vbApplicationModal"

VBA MsgBox vbApplicationModal example

vbSystemModal

Value 4096. Every application is suspended until the user responds. Use sparingly — it is intrusive.

MsgBox "Thanks for visiting Analysistabs!", vbSystemModal, "vbSystemModal"

VBA MsgBox vbSystemModal example

vbMsgBoxHelpButton

Value 16384. Adds a Help button. Supply helpfile and context arguments for it to do anything.

MsgBox "Thanks for visiting Analysistabs!", vbMsgBoxHelpButton, "vbMsgBoxHelpButton"

VBA MsgBox vbMsgBoxHelpButton example showing a Help button

VbMsgBoxSetForeground

Value 65536. Forces the message box to the front. Useful when a long macro has run in the background and the window might otherwise appear behind another application.

MsgBox "Thanks for visiting Analysistabs!", vbMsgBoxSetForeground, "VbMsgBoxSetForeground"

VBA MsgBox VbMsgBoxSetForeground example

vbMsgBoxRight

Value 524288. Right-aligns the message text.

MsgBox "The input data is not valid!", vbMsgBoxRight, "vbMsgBoxRight"

VBA MsgBox vbMsgBoxRight example with right-aligned text

vbMsgBoxRtlReading

Value 1048576. Sets right-to-left reading order on Hebrew and Arabic systems.

MsgBox "Thanks for visiting Analysistabs!", vbMsgBoxRtlReading, "vbMsgBoxRtlReading"

VBA MsgBox vbMsgBoxRtlReading example with right-to-left text

VBA MsgBox for error handling

A message box is the simplest way to surface a runtime error while you are still developing. Jump to a label with On Error GoTo and report the error number and description.

Sub ShowErrorMessageBox()

    On Error GoTo ErrorHandler

    ' Your code goes here

    Exit Sub

ErrorHandler:
    MsgBox "Error " & Err.Number & vbCr & Err.Description, _
           vbCritical, "Something went wrong"

End Sub

The Exit Sub before the label is not optional

Without it, the error handler runs every time the procedure completes normally, and you get an error message with a blank description. This is the most common mistake in VBA error handling.

Custom message box in Excel VBA

If none of the standard combinations fit — you need three custom button captions, a checkbox, an input field, or formatted text — build a UserForm instead. A UserForm gives you full control over layout, fonts and colours, and can return whatever you like.

Custom message box built with a UserForm in Excel VBA

The MsgBox function cannot change button captions, remove buttons entirely, or set font size and colour. Those all require a UserForm.

How to run these examples

  1. Open the VBA editorPress Alt + F11 in Excel, or Fn + Option + F11 on Mac.
  2. Insert a moduleInsert → Module from the menu. Do not paste into ThisWorkbook unless the example says so.
  3. Paste the codeCopy any example above and paste it into the module window.
  4. Run itClick inside the procedure and press F5.

UserForm controls

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
Project Management Templates

All-in-One Pack
120+ Project Management Templates

Essential Pack
50+ PM 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
Published On: August 25, 2013Categories: VBATags: , , , , Last Updated: July 31, 2026

About the Author: PNRao

Hi, I’m PNRao—an Excel & VBA developer with 20 years in data mining, automation, and project management. Day-to-day I turn raw data into clear insight, replace repetitive work with one-click workflows, and guide teams with smarter project management. On Analysistabs.com I share battle-tested tips on Excel, VBA, SQL, Automation, Project Management, and Data Analysis—plus a growing library of free and premium Project Management Templates. My goal is to help you work faster, build sharper tools, and level up your career. Let's master data and manage projects effectively, together.

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. Nabil Mourad June 4, 2017 at 5:56 PM - Reply

    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

Leave A Comment