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 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
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
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
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
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
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 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
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
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
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 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"
vbDefaultButton2
Value 256. Focus on the second button.
MsgBox "Close the file and try again?", vbRetryCancel + vbDefaultButton2, "vbDefaultButton2"
vbDefaultButton3
Value 512. Focus on the third button.
MsgBox "Close the file and try again?", vbYesNoCancel + vbDefaultButton3, "vbDefaultButton3"
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"
vbSystemModal
Value 4096. Every application is suspended until the user responds. Use sparingly — it is intrusive.
MsgBox "Thanks for visiting Analysistabs!", vbSystemModal, "vbSystemModal"
vbMsgBoxHelpButton
Value 16384. Adds a Help button. Supply helpfile and context arguments for it to do anything.
MsgBox "Thanks for visiting Analysistabs!", vbMsgBoxHelpButton, "vbMsgBoxHelpButton"
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"
vbMsgBoxRight
Value 524288. Right-aligns the message text.
MsgBox "The input data is not valid!", vbMsgBoxRight, "vbMsgBoxRight"
vbMsgBoxRtlReading
Value 1048576. Sets right-to-left reading order on Hebrew and Arabic systems.
MsgBox "Thanks for visiting Analysistabs!", vbMsgBoxRtlReading, "vbMsgBoxRtlReading"
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.
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
-
Open the VBA editorPress Alt + F11 in Excel, or Fn + Option + F11 on Mac.
-
Insert a moduleInsert → Module from the menu. Do not paste into ThisWorkbook unless the example says so.
-
Paste the codeCopy any example above and paste it into the module window.
-
Run itClick inside the procedure and press F5.
Related VBA guides
- VBA InputBox — when you need the user to type something rather than pick a button.
- VBA Open File dialog box — let the user browse for a file.
- VBA If Then Else — the branching that makes a message box useful.
- VBA On Error — full error handling beyond a message box.
- 100+ Excel VBA macro examples — the full library.
























Thanks friend. It helped me a lot.I appreciate your efforts on creating useful VBA codes.
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?
Hi Ramana,
You can use a Boolean variable to do this:
Instead of this flag, you may use any other condition when you want to show the Message box.
Thanks-PNRao!
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.
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 SubThanks-PNRao!
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
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. .
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.
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?
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
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.
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?
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
Sub DisplayUserName()
msgBox “The User Name is: ” & Environ(“UserName”),vbInformation,”User Name”
End Sub
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”
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)
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)
.
Very helpful. Perfect Macros. Thanks you.
can give msg box button a person name.. just like yes no or ok cancel
thanks