In Excel VBA, use MsgBox to show a pop-up message or ask a user a simple question. Call it with a prompt, optional buttons and icon, and an optional title; when the user responds, VBA can use the returned value to decide what to do next.
What MsgBox does
MsgBox is a built-in VBA function that displays a modal dialog: while the dialog is open, the user must respond to it before continuing to work in the calling procedure. It is useful for brief instructions, completion notices, warnings, and small decisions such as confirming whether to continue. It is not a way to display information inside a worksheet cell, and it is not a replacement for a custom form when a workflow needs several inputs.
The message itself is plain text. You can include line breaks, choose a limited set of standard buttons and icons, and set the window title. If the user clicks a button, presses an applicable key, or closes the dialog, the function returns a value identifying the response. That return value is what makes a yes/no or retry/cancel box useful in program logic.
How to add and run VBA code in Excel
In Excel for Microsoft 365 on Windows, open the Visual Basic Editor with Alt+F11. In the editor, choose Insert > Module, then place a procedure in the module. To run a macro from Excel, use Alt+F8, select its name, and choose Run. If the Developer tab is missing, enable it through File > Options > Customize Ribbon and select Developer.
On Excel for Mac, the Visual Basic Editor shortcut is commonly Option+F11; on some keyboards you may also need Fn. The macro dialog shortcut is commonly Option+F8. Keyboard settings and hardware can affect these combinations, so use the Developer tab or Excel’s Tools menu if a shortcut does not work. Excel for the web can open and edit workbooks containing macros, but it cannot create, edit, or run VBA macros; use the desktop application.
Here is a minimal example. It declares a string, assigns the message, and displays it with an information icon and a custom title:
Sub ShowWelcome()
' Display a short welcome message.
Dim messageText As String
messageText = "Welcome to the workbook."
MsgBox messageText, vbOKOnly + vbInformation, "Welcome"
End Sub
Before running any macro that might change data, save a copy of the workbook. Macro changes cannot be reversed with Excel’s Ctrl+Z undo command; a message box does not make the procedure’s other actions undoable.
Syntax and arguments
The general syntax is MsgBox(prompt, buttons, title, helpfile, context). Only prompt is required. You can omit later optional arguments, but commas are needed if you want to supply a later argument while skipping one before it. In everyday Excel macros, the first three arguments cover nearly all uses.
- prompt: The text shown in the dialog. It can be a string variable or a string expression. Keep it short and specific.
- buttons: An optional combination of constants that sets the available buttons, icon, default button, and some display behavior. If omitted, the box uses the standard OK button.
- title: Optional text shown in the dialog’s title bar. Supplying a meaningful title helps identify which task raised the message.
- helpfile and context: Optional arguments for associating the dialog with a Help file and topic. Most workbook macros do not need them.
For example, vbOKOnly + vbInformation combines the OK-only button choice with an information icon. The plus sign is commonly used to combine these VBA constants. Choose one button-group option and, if desired, one icon option, plus a default-button option; do not add several mutually exclusive button groups together.
Choosing buttons, icons, and a default
Pick buttons that match the decision the macro can actually handle. Common button constants include vbOKOnly, vbOKCancel, vbYesNo, vbYesNoCancel, vbRetryCancel, and vbAbortRetryIgnore. The constants describe the choices displayed, not what your code will do: your procedure must still check the returned value and implement the corresponding action.
For a visual cue, VBA provides vbInformation, vbExclamation, vbCritical, and vbQuestion. Use an icon to reinforce the meaning, not as the only way to communicate severity. A reader should understand the message from its words even if an icon is overlooked or rendered differently.
To set which button is initially selected, add a default-button constant such as vbDefaultButton1 or vbDefaultButton2. In a Yes/No dialog, the second button is No, so setting the second button as default can reduce accidental confirmation. Avoid choosing a risky action as the default. The default is a keyboard and focus choice; it does not itself make the response happen.
Capture the response and branch safely
Assign the result to a variable declared as VbMsgBoxResult. For a Yes/No question, compare it with vbYes and vbNo, rather than relying on the order or numeric values of the constants. This makes the intent clearer and easier to maintain if the dialog changes.
Sub ConfirmWork()
' Continue only when the user explicitly chooses Yes.
Dim answer As VbMsgBoxResult
answer = MsgBox("Continue with the update?", _
vbYesNo + vbQuestion + vbDefaultButton2, _
"Confirm update")
If answer = vbYes Then
MsgBox "The update can continue.", vbOKOnly + vbInformation, "Status"
ElseIf answer = vbNo Then
MsgBox "No changes were requested.", vbOKOnly, "Status"
End If
End Sub
The final If branch here handles both buttons explicitly. If the dialog instead has a Cancel button, include a corresponding ElseIf answer = vbCancel Then branch when cancellation needs a distinct response. Do not assume that every dialog has the same return choices: the available results depend on the buttons shown. Handling the choices deliberately prevents a procedure from treating cancellation as approval.
Writing prompts people can act on
A useful prompt names the situation and the consequence, then gives the user an unambiguous choice. For example, “Delete the selected rows?” is less informative than “Delete the 12 selected rows? This cannot be undone.” Avoid vague messages such as “Are you sure?” when the user cannot tell what they are confirming. Do not use a Yes/No box for a choice with more than two meaningful outcomes.
You can build a message from multiple lines with vbCrLf. Keep the key fact near the beginning because long prompts are harder to scan and may be clipped or displayed awkwardly on some systems. A short example is:
Sub ShowImportNotice()
' Separate the heading and detail onto different lines.
Dim messageText As String
messageText = "Import complete." & vbCrLf & _
"Review the new rows before sharing the file."
MsgBox messageText, vbOKOnly + vbInformation, "Import status"
End Sub
Use a consistent title, avoid unexplained abbreviations, and do not put sensitive information in a pop-up if other people can see the screen. A message box is transient: it is not a durable record of a warning or decision. If the user needs a record, write appropriate information to a worksheet or another approved location as well.
Common problems and misconceptions
- The macro does not run: Check that the workbook is opened in desktop Excel and that macros are permitted by the organization’s security settings. A file saved as an ordinary
.xlsxworkbook cannot store VBA code; use a macro-enabled format such as.xlsmwhen the workbook needs to retain macros. - The dialog appears at an unexpected time: A call inside a loop, worksheet event, or repeatedly triggered procedure may show the box more than once. Check the procedure’s control flow and events rather than adding more message boxes to diagnose it.
- The result is ignored: Calling
MsgBoxwithout assigning its result is fine for a notice, but it cannot support a decision. Store the return value and compare it with named constants when the user has a choice. - A message box is used in a worksheet formula:
MsgBoxis a VBA function for procedures, not an Excel worksheet function. It is also a poor fit for a user-defined function called from a cell because recalculation can occur unexpectedly and worksheet functions are expected to return values rather than interrupt users. - Ctrl+Z does not reverse a macro: Excel’s undo history generally does not restore workbook changes made by VBA. Save a separate copy before running code that edits or deletes content.
For unattended or scheduled automation, avoid relying on a modal message box. It can wait indefinitely for someone to click a button, leaving the macro or automation process stalled. Record status in a log, a worksheet, or another suitable output instead.
When to use a form or another alternative
MsgBox works well for a brief notice or a one-step confirmation. Use an InputBox when you need one simple text value, while remembering that it is still a limited dialog and needs validation. Use a VBA UserForm when the task needs several fields, input validation, lists, custom buttons, or a more carefully controlled layout. For persistent guidance, place instructions on a worksheet rather than repeatedly interrupting the user with pop-ups.
Choose the least disruptive option that still prevents mistakes. A completion notice may be unnecessary if the workbook already displays a clear status. A destructive operation, by contrast, may warrant a confirmation that states exactly what will be affected. For accessibility and usability, keep labels descriptive and do not depend only on color, sound, or an icon to explain the choice.
Frequently Asked Questions
What is the simplest MsgBox code in VBA?
Use MsgBox followed by a quoted message, such as MsgBox "Done". In a macro, you can add a title and button or icon settings as optional arguments.
How do I make a Yes/No message box in VBA?
Set the buttons argument to vbYesNo, optionally combined with an icon such as vbQuestion. Assign the result to a VbMsgBoxResult variable and test it against vbYes or vbNo.
How do I change the MsgBox title?
Provide the title as the third argument: for example, MsgBox "Saved", vbOKOnly, "Workbook status". The title appears in the dialog’s title bar.
Can I change the text on MsgBox buttons?
No. The built-in MsgBox function offers predefined button labels and combinations; it does not let you rename those buttons. Use a VBA UserForm if custom button captions are required.
Does MsgBox work in Excel for the web?
No. Excel for the web does not run VBA macros. Open the workbook in desktop Excel to use code that displays a VBA message box.
Related
- Microsoft Excel Named Ranges: How They Work and Help
- Microsoft Excel CSV Import: Steps, Settings, and Fixes
- Microsoft Excel Insert Page Break: A Practical Guide
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel VBA: What It Does, How It Works, and When to Use ItExcel VBA is the programming language built into the desktop versions of Microsoft Excel for automating tasks and…
- VBA: How to Find an Accredited VA PractitionerIf by VBA you mean the U.S. Department of Veterans Affairs’ Veterans Benefits Administration, use VA’s official accreditation…
- Excel VBA: How to Turn Off Error HandlingTo turn off an error handler in the current Excel VBA procedure, use On Error GoTo 0. It…
- Sort Columns in Excel with VBAYes. In Excel VBA, use the Sort object to sort entire rows by values in a chosen column,…
- Excel VBA List Worksheet Names: Methods and ExamplesTo list worksheet names with Excel VBA, loop through the workbook’s Worksheets collection and read each sheet’s Name…
- Excel VBA: Show a UserForm When the Workbook OpensTo show an Excel VBA UserForm when a workbook opens, put a Workbook_Open event procedure in the ThisWorkbook…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.