Excel VBA’s MsgBox function displays a message and can return the button the user clicks. For example, use MsgBox "Report complete", vbInformation, "Status" for a simple notice, or store its return value to make a Yes/No choice control what your macro does.
What a VBA MsgBox Does
A message box is a small dialog that pauses a running macro until the user responds. It is useful for confirmations, short instructions, warnings, and simple choices. Unlike a cell note or a message written to a worksheet, it appears immediately and asks the user to deal with it before the macro continues.
In Excel for Microsoft 365 on Windows, you can enter VBA in the Visual Basic Editor, reached with Alt+F11, then choose Insert > Module. Put a procedure in the module and run it from the editor or Excel’s macro list. The Developer tab may need to be enabled to access Visual Basic and Macros from the ribbon. Excel for the web cannot create or run VBA macros; Excel for Mac supports VBA, although some commands and object-model features can differ from Windows.
Before running a macro, save a copy of the workbook. VBA changes cannot be reversed with Ctrl+Z, and a macro may alter cells or other workbook content before showing a message. Save a workbook containing macros as an Excel Macro-Enabled Workbook (*.xlsm) if you need to keep its VBA code.
Basic MsgBox Syntax
The general form is MsgBox(prompt, buttons, title). The prompt is the message text; buttons specifies the button set, icon, and default button; and title supplies the text in the dialog’s title bar. The buttons and title arguments are optional, but adding a clear title helps users understand what the message concerns. The function can also accept optional help-file and context arguments, which are mainly relevant to applications that provide a help system.
This short procedure displays a notice with one OK button and an information icon:
Sub ShowCompletionNotice()
' Display a simple status message.
MsgBox "The monthly report is ready.", vbInformation, "Report status"
End Sub
VBA displays the message when execution reaches the line. It does not continue to the next line until the user closes the dialog. Use that pause intentionally: a dialog is appropriate when a person must read or choose something, but it can be disruptive if a macro displays one for every row in a large data set.
Choose Buttons, Icons, and a Default
The buttons argument combines values using +. For example, vbYesNo + vbQuestion creates Yes and No buttons with a question icon. Common button constants include:
vbOKOnlydisplays OK, and is the default button set when no button type is specified.vbOKCancel,vbYesNo, andvbYesNoCanceloffer the corresponding choices.vbAbortRetryIgnoreandvbRetryCancelare available for situations where those actions genuinely make sense.
Common icon constants are vbInformation, vbQuestion, vbExclamation, and vbCritical. Choose an icon that reinforces the meaning rather than using a warning symbol for ordinary progress. To set the initially selected button, add a default-button constant such as vbDefaultButton2. For instance, the following makes No the default choice:
Sub ConfirmArchive()
' Make No the default to reduce accidental confirmation.
MsgBox "Archive the selected records?", _
vbYesNo + vbQuestion + vbDefaultButton2, _
"Confirm archive"
End Sub
The default button is the one activated by pressing Enter; it is not a substitute for checking the user’s actual choice in code. Use the available button combinations to match the action. For example, a Yes/No dialog is not suitable if the user must also be able to cancel without choosing either option.
Read the User’s Response
MsgBox returns a number corresponding to the button pressed. Compare that result with named constants such as vbYes, vbNo, vbOK, and vbCancel rather than relying on numeric values. This makes the intent easier to read and reduces mistakes when the button configuration changes.
Sub ConfirmAndContinue()
Dim answer As VbMsgBoxResult
' Ask before making a change that should be deliberate.
answer = MsgBox("Continue with the update?", _
vbYesNo + vbQuestion + vbDefaultButton2, _
"Confirm update")
If answer = vbYes Then
MsgBox "The update can now proceed.", vbInformation, "Next step"
Else
MsgBox "No changes were requested.", vbInformation, "Cancelled"
End If
End Sub
The variable is declared as VbMsgBoxResult, an enumeration designed for message-box results. In this example, the macro distinguishes Yes from No and gives a separate response for each. In a real workbook, replace the second notice with the work that should happen after confirmation. Keep potentially destructive actions inside the confirmed branch, not before the question.
For a three-button choice, test each possible result. A dialog using vbYesNoCancel can return vbYes, vbNo, or vbCancel. Treat Cancel as its own outcome; do not let it accidentally fall through to code intended for Yes.
Make Messages Easier to Read
Keep the prompt brief and specific: identify what is happening and, where relevant, what the user should do. A title such as “Export complete” is more useful than a generic “Message.” Avoid vague prompts like “Are you sure?” when several actions are possible; name the action instead, such as “Delete the selected rows?”
For a message that needs more than one line, join text with vbCrLf. For example:
Sub ShowImportSummary()
Dim message As String
' Separate the outcome from the next instruction.
message = "Import finished." & vbCrLf & _
"Review the Exceptions sheet for skipped rows."
MsgBox message, vbInformation, "Import summary"
End Sub
When building a prompt from a cell value, consider what happens if the cell is blank or contains unexpectedly long text. A dialog is best for concise feedback, not for presenting a full report. Put detailed results in a worksheet and use the message box to point the user to them.
Common Problems and How to Avoid Them
- The macro stops at the message. This is normal: the dialog is modal, so the procedure waits for a response. Close the box to let execution continue.
- The macro ignores the choice. A message displayed as a statement does not automatically control the procedure. Assign the returned result to a variable, then use an
Ifstatement orSelect Caseto branch. - The wrong button is assumed. Compare the result to constants such as
vbYesorvbCancel. Do not assume the first or leftmost button means approval without checking the configured buttons. - The prompt is hard to scan. Use a meaningful title, short sentences, and line breaks where helpful. Move lengthy explanation or tabular output to the worksheet.
- The macro will not run. Confirm that the file is macro-enabled, that macros are permitted by the workbook’s security settings, and that the code is in a standard module if you intend to run it as a normal macro. Do not enable macros in an untrusted file just to see its message box.
Message boxes are not a replacement for input validation or error handling. A “Completed” message should appear only after the relevant work has actually succeeded. If a procedure can fail, handle or report the error appropriately rather than showing a success message regardless of the outcome.
MsgBox Compared with Other VBA Dialogs
Use MsgBox when the user needs to read a short message or choose among a small set of fixed buttons. If the macro needs a typed value, a message box is not an input form: consider VBA’s InputBox function for a simple prompt, or a UserForm when you need several fields, validation, or a more structured interface.
For selecting a file, use an appropriate file dialog rather than asking users to type a path into a message box. For detailed feedback, write results to cells or a dedicated report sheet. These alternatives make sense because a message box has a limited purpose: it interrupts the workflow to convey a concise message or obtain a simple response.
Frequently Asked Questions
How do I show a MsgBox in Excel VBA?
Place a line such as MsgBox "Hello", vbInformation, "Welcome" in a VBA procedure and run the procedure. In Windows Excel, open the Visual Basic Editor with Alt+F11 and insert a standard module if needed.
How do I make a Yes/No MsgBox in Excel VBA?
Use vbYesNo in the buttons argument, usually with an icon such as vbQuestion. Store the result and compare it with vbYes or vbNo to decide what the macro should do.
How can I tell which MsgBox button was clicked?
Assign the function’s return value to a variable, then compare it with the appropriate result constant, for example vbOK, vbYes, or vbCancel. The returned value is not the button caption as text.
Can I change the MsgBox title or add a line break?
Yes. Supply a title as the third argument, and join message lines with vbCrLf. Keep the prompt concise and put extensive details in the workbook.
Do VBA MsgBox macros work in Excel for the web?
No. Excel for the web does not run VBA macros. Use desktop Excel for VBA; Excel for Mac supports VBA, but some platform-specific VBA behavior may differ.
Related
- Excel Not Responding: Should You Wait or Force Quit?
- Excel Not Responding? How to Protect and Recover Work
- Excel Not Responding: How Long Should You Wait?
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel UserForm Keeps Changing Size? Causes and FixesAn Excel UserForm usually changes size because VBA or its AutoSize setting changes its dimensions, or because Windows…
- Excel VBA Mail Merge to Word: Setup, Code, and TipsYes. In Excel for Microsoft 365 on Windows, VBA can open a Word mail-merge template connected to an…
- Excel VBA UserForm Animation Effects: What Really WorksExcel VBA UserForms have no built-in animation setting for effects such as fading, sliding, or zooming. You can…
- VBA Range Object: How to Work with CellsThe Excel VBA Range object represents one or more cells on a worksheet, letting code read or change…
- Excel VBA Reset Error Handling: What Err.Clear DoesTo turn off an active VBA error handler in the current procedure, use On Error GoTo 0. Use…
- Vba loop through rows?Learn how to loop through Excel rows with VBA, find the last row, handle conditions and deletions, and…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.