A VBA MsgBox string is the text you pass to the MsgBox function to display a message in a dialog box. Build it from quoted text and variables with the & operator, then pass it as the prompt—for example, MsgBox "Hello, " & userName.
What a VBA MsgBox string is
In Excel VBA, a message box is a simple way to show information, ask a basic question, or pause a macro until someone responds. Its prompt can be a literal string, a String variable, or an expression that evaluates to text. The string determines the message displayed inside the dialog; separate arguments can set its buttons, icon, and title.
A short message can be passed directly, while a longer or changing message is usually easier to manage in a variable. A variable also lets you assemble text from worksheet values, dates, counts, or other results before displaying it. The message box is still a dialog, not a worksheet cell: it appears over Excel and typically stops the macro while it waits for a response.
For example, MsgBox "Import complete." displays fixed text. If the text depends on a value stored in customerName, join the pieces together: MsgBox "Hello, " & customerName. The variable must be assigned a value before the message is shown if you want meaningful text.
MsgBox syntax and its arguments
The general VBA syntax is MsgBox(prompt, buttons, title, helpfile, context). Only prompt is required; the other arguments are optional. For everyday Excel macros, the first three are the ones most often used:
promptis the message string shown in the dialog.buttonscontrols which buttons and icon appear, and can specify the default button. If omitted, VBA displays an OK button.titlesets the text in the dialog’s title bar. If omitted, the application name is used.
The optional helpfile and context arguments link the message box to a help topic. They are intended for applications that provide a compiled help file and are rarely needed in a typical workbook macro. If you supply a context, you also need to provide the relevant help file.
VBA’s calling syntax depends on whether you use the return value. When you simply show a message, write MsgBox message without parentheses around the arguments. When you assign the response, write answer = MsgBox(message, vbYesNo), with parentheses. This difference is a frequent source of compile errors when a line is changed from displaying a message to capturing a choice.
Build a message from text and variables
Use the ampersand operator, &, to join text and variable values. It is the clear, standard choice for string concatenation in VBA. The plus sign can sometimes combine strings, but it can also mean numeric addition and may behave unexpectedly when values are not the types you intend. Prefer & when your purpose is to construct text.
This example creates a two-line welcome message from a variable. The comment explains the operation, and every variable is declared so the code can be used in a module with Option Explicit.
Sub ShowWelcome()
Dim userName As String
Dim message As String
userName = "Mina"
message = "Welcome, " & userName & "!" & vbCrLf & _
"Choose OK to continue."
' Display the completed string with an information icon.
MsgBox message, vbInformation, "Workbook status"
End Sub
The first line of the prompt is assembled from fixed text and the value of userName. The & operator joins those pieces without adding spaces automatically, so include spaces and punctuation in the quoted text where they belong. If the variable contains Mina, the dialog begins “Welcome, Mina!”
For values that are not strings, convert deliberately when clarity matters. For instance, use CStr to turn a numeric count into text before joining it to a sentence. Also consider how a date or currency value should appear: a raw conversion may not match the display format users expect. Format the value explicitly before combining it if the message needs a particular date or number style.
Add line breaks and quotation marks
A prompt can contain multiple lines. In Windows VBA, vbCrLf is a common line-break constant, while vbNewLine represents the platform’s newline sequence. Join the line break between the text sections with &. You can also use vbTab to insert a tab, though tabs are not a dependable way to align columns in a dialog because character widths vary.
To include a literal quotation mark inside a VBA string, double it. For example, the VBA expression "She said, ""Ready?""" evaluates to the text She said, "Ready?". Each pair of quotation marks inside the string represents one displayed quotation mark. This rule applies to ordinary VBA string literals, not just to messages.
Keep a dialog readable by using short sentences and natural line breaks rather than trying to format it like a report. A MsgBox is intended for brief prompts; long instructions are harder to scan and may not fit comfortably. If the message needs headings, links, extensive formatting, or several controls, a worksheet area or a custom UserForm is usually more suitable.
Choose buttons, icons, and a title
The buttons argument accepts built-in VBA constants. You can combine a button group, an icon, and a default-button setting with the Or operator. For example, a confirmation dialog can offer Yes and No, show a question icon, and make No the default selection:
Sub ConfirmSave()
Dim answer As VbMsgBoxResult
' Offer a cautious default for this confirmation.
answer = MsgBox("Save the changes now?", _
vbYesNo Or vbQuestion Or vbDefaultButton2, _
"Confirm save")
If answer = vbYes Then
MsgBox "Continue with the save operation.", vbInformation, "Next step"
End If
End Sub
The constants make code easier to understand than unexplained numeric button codes. Common button groups include vbOKOnly, vbOKCancel, vbYesNo, and vbYesNoCancel. Common icons include vbInformation, vbExclamation, vbQuestion, and vbCritical. A default-button constant such as vbDefaultButton2 selects which button is initially highlighted; it does not remove the other choices.
Choose buttons that match the action your macro can actually perform. A Yes/No box should not imply that both answers are handled if the code only responds to Yes. Likewise, use a descriptive title such as “Confirm save” instead of relying on a generic application title. The title adds context but does not replace a clear prompt.
Read the response returned by MsgBox
MsgBox returns a value of the VbMsgBoxResult type, identifying the button selected. For a Yes/No prompt, compare the result with vbYes or vbNo; for an OK/Cancel prompt, compare it with vbOK or vbCancel. Checking named constants is clearer and safer than relying on numeric values.
Displaying a message and capturing a response are different tasks. If you call MsgBox without assigning its result, the macro shows the dialog but discards the selected button. Assign the result to a variable when the next step depends on the choice. An If or Select Case statement can then handle each possible response.
For three-button dialogs, account for all three results. A user may choose Cancel or close the dialog, depending on the available buttons and dialog style. Do not assume that a confirmation was accepted merely because the message box has disappeared. Explicit response handling helps prevent a macro from continuing with an unintended action.
Common string problems and fixes
If a message is blank or incomplete, first inspect the variable values used to build it. A String variable that has not been assigned contains an empty string, so concatenating it adds no visible text. If text comes from a cell, check that the cell contains the expected value and that the correct worksheet and cell are referenced. A cell containing an Excel error value may also need to be handled before converting it to a string.
- Missing spaces: VBA does not insert spaces between joined pieces. Add a space at the end of one quoted section or the start of the next.
- Unexpected addition: Use
&to join text rather than+, which may be interpreted as arithmetic. - Compile error near quotation marks: Double quotation marks that should appear inside a VBA string, and check that the opening and closing quotes are balanced.
- Wrong button behavior: Store the result and compare it with the matching named constant, such as
vbYes, rather than assuming the user selected the affirmative option. - Hard-to-read message: Split it into concise lines with
vbCrLf, or use a worksheet or form if it requires substantial content.
When a message is assembled from several parts, build and inspect the prompt variable before calling MsgBox. This makes it easier to identify whether a problem lies in the source values, the concatenation, or the dialog settings. In the VBA editor, stepping through the procedure can help you see the values at each line; avoid displaying sensitive data during debugging.
MsgBox compared with InputBox and UserForms
A MsgBox displays information and returns a button choice. It does not provide a text field for someone to type an answer. Use VBA’s InputBox when a simple text response is needed, keeping in mind that the returned value is text and that cancellation or an empty response needs thoughtful handling.
Use a UserForm when a task needs multiple fields, validation, custom labels, or a more deliberate layout. A UserForm takes more setup than a MsgBox but can guide users through a more complex interaction. A worksheet can be better still when information should remain visible, be edited later, or be printed. The useful rule is to keep MsgBox prompts short and reserve them for a brief notice or decision that truly needs to interrupt the macro.
Safety and good macro practice
A confirmation dialog can reduce accidental actions, but it is not a substitute for safe macro design. Make sure the code responds correctly to every button choice, and do not use a message box to request or display passwords, account credentials, or other secrets. Dialog text can be visible to anyone looking at the screen, and macros may also write information to logs or worksheets.
Before running a macro that changes workbook data, save a separate copy of the workbook. VBA macros cannot be undone with Ctrl+Z, so a message box does not provide a reliable recovery mechanism. Test changes on sample data or a duplicate workbook, especially when the macro deletes, overwrites, or moves information. Use trusted workbooks and follow your organization’s macro-security rules.
Frequently Asked Questions
How do I store a MsgBox message in a VBA string variable?
Declare a variable with Dim message As String, assign text to it, and pass it to MsgBox message. Join multiple text sections or variable values with &.
How do I add a new line in a VBA MsgBox?
Join the message sections with vbCrLf, for example "First line" & vbCrLf & "Second line". The dialog then displays the sections on separate lines.
How do I show a variable in a MsgBox?
Concatenate the variable with quoted text, such as MsgBox "Rows processed: " & CStr(rowCount). For dates, currency, or other formatted values, prepare the display text deliberately before joining it.
How do I get a Yes or No answer from MsgBox?
Assign the function’s result to a VbMsgBoxResult variable, use a Yes/No button group, and compare the result with vbYes or vbNo. The result tells your code which button was selected.
Can MsgBox accept a string directly?
Yes. A quoted string such as MsgBox "Finished." is a valid prompt. Use a variable or an expression when the message needs to include changing values or multiple lines.
Related
- Data Validation and Verification in Excel Explained
- Power Query Replace Text: Steps, Options, and Examples
- Conditional Formatting: Use More Than One Rule in Excel
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- VBA Array: Find a Value and Get Its Index in ExcelTo find a value in a VBA array and get its index, loop from LBound to UBound and…
- Automatically Add Comments to Excel Cells with VBAYes. In desktop Excel, VBA can automatically add a note to a cell with Range.AddComment; in current Microsoft…
- Excel Macros in Google Sheets: What Works?No: Google Sheets cannot run Excel VBA macros, even when you open an Excel workbook that contains them.…
- Make a Plot with a Dictionary in VBA: Excel GuideYes. In Excel for Microsoft 365 on Windows, use a VBA Scripting.Dictionary to group records by category, write…
- VBA Find Last Used Column in Excel: Reliable MethodsTo find the last used column anywhere on an Excel worksheet with VBA, use Range.Find with SearchOrder:=xlByColumns and…
- VBA Check If Workbook Exists: Paths, Files, and ErrorsYes. In VBA, use Dir$ with the workbook’s full file path and check whether it returns an empty…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.