To display a VBA variable in a message box, use MsgBox variableName, or combine a label and the value with MsgBox "Value: " & variableName. In VBA, MsgBox displays text on screen; Debug.Print sends text to the Immediate window, so it is not the same as a message box.
What “print a variable” means in VBA
People often use “print” informally to mean “show” or “output.” If you want a pop-up containing a variable’s value, the relevant VBA function is MsgBox. It evaluates the expression you give it and displays the result in a dialog. The expression can be a variable by itself, a text string, or a combination of text and values.
For example, if a variable called customerName contains Jordan, then MsgBox customerName displays Jordan. To make the result clearer, add a label: MsgBox "Customer: " & customerName. The ampersand joins strings and values into one message.
VBA does have other kinds of output. Debug.Print is useful while developing because it writes to the Immediate window in the Visual Basic Editor. A VBA Print statement can also be used in particular contexts, such as writing to a file, but neither is the usual way to show a pop-up. Choose the output method according to where you want the information to appear.
Basic MsgBox syntax
The shortest form is MsgBox prompt, where prompt is the message to display. The prompt can be a string literal, a variable, or a concatenated expression. For example, these are different ways to show a value:
MsgBox userNamedisplays the variable by itself.MsgBox "User: " & userNameadds a descriptive label.MsgBox "Items: " & itemCount & "; total: " & totalcombines multiple values.
The complete function form is MsgBox(prompt, buttons, title, helpfile, context). The prompt is required; the other arguments are optional. The buttons argument controls the buttons and icon, while title sets the text in the dialog’s title bar. You can omit optional arguments when you do not need them.
In a normal Excel macro, put the statement inside a procedure. Declare variables with Dim; using Option Explicit at the top of a module helps VBA catch misspelled or undeclared variable names instead of silently treating them as new variables.
A complete Excel example
This macro reads a value from cell B2 on Sheet1 and displays it with a label. It assumes the worksheet exists and that the cell contains ordinary text or a number. The variable is declared as a Variant so it can receive either kind of cell value.
Option Explicit
Sub ShowCellValue()
Dim cellValue As Variant
' Read the value from the worksheet.
cellValue = ThisWorkbook.Worksheets("Sheet1").Range("B2").Value
' Display a label and the value in a message box.
MsgBox "B2 contains: " & CStr(cellValue), vbInformation, "Cell value"
End Sub
CStr converts the value to a string before it is joined to the label. For ordinary text and numeric values, this makes the intended conversion explicit. If B2 might contain an Excel error value, check it with IsError before converting it; an error value cannot be handled like ordinary display text.
In Excel for Microsoft 365 on Windows, open the Visual Basic Editor with Alt+F11, insert a standard module, and place the procedure there. You can also use Developer > Visual Basic. On a Mac, the Visual Basic Editor is available from Developer > Visual Basic; the shortcut is commonly Option+F11, though some keyboards require the Fn key as well. The macro’s MsgBox behavior is the same on Windows and Mac.
Joining text and multiple variables
Use the ampersand operator (&) to assemble a readable message from several parts. It is the clearest choice for string concatenation in VBA. The plus sign can perform numeric addition and can make an expression harder to interpret, so avoid using it to join a label to a variable.
For example, this procedure displays a person’s name and an order count in one dialog. The values below are assigned inside the procedure so the example can run as written.
Sub ShowOrderSummary()
Dim customerName As String
Dim orderCount As Long
' Set sample values for the message.
customerName = "Jordan Lee"
orderCount = 4
' Join labels and values into one prompt.
MsgBox "Customer: " & customerName & vbCrLf & _
"Orders: " & CStr(orderCount), vbOKOnly, "Order summary"
End Sub
The underscore continues a VBA statement onto the next line; it must be preceded by a space. vbCrLf inserts a line break, so the name and count appear on separate lines in the same dialog. You can also build the message in a separate String variable if a longer prompt would otherwise be difficult to read.
Formatting numbers, dates, and currency
A variable’s stored value and its display format are not always the same thing. A numeric variable may contain a decimal value, while the message needs a fixed number of decimal places or a thousands separator. Use Format$ to create a display string before joining it to the rest of the prompt.
For instance, Format$(amount, "#,##0.00") formats a number with two decimal places. A date can be displayed with a pattern such as Format$(dueDate, "mmmm d, yyyy"). The exact punctuation used for decimal and thousands separators can follow the computer’s regional settings, so the appearance may differ between systems.
For a currency example, first set the value and then format it for display:
Sub ShowAmount()
Dim amount As Currency
' Set an illustrative amount.
amount = 1234.5
' Format the value for the message.
MsgBox "Amount: $" & Format$(amount, "#,##0.00"), _
vbInformation, "Amount"
End Sub
This displays an amount with two decimal places, such as $1,234.50 under typical English-language regional settings. The dollar sign in this example is literal text; change it if another currency symbol or a currency-neutral display is more appropriate. Formatting changes how the value is shown, not the value stored in the variable.
Adding a title, icon, or response buttons
A message box can do more than show a value. Its optional arguments let you add a title, choose an icon, and offer buttons. For example, vbInformation requests an information icon, and vbOKOnly makes the available response explicit. These constants are built into VBA.
If you use buttons that ask a question, capture the result. The function returns a value identifying the button the user selected. For a Yes/No dialog, compare that result with vbYes or vbNo rather than assuming the user chose one particular response.
Sub ConfirmAction()
Dim answer As VbMsgBoxResult
' Ask before continuing.
answer = MsgBox("Continue with this action?", _
vbYesNo + vbQuestion, "Confirm")
' Respond to the selected button.
If answer = vbYes Then
MsgBox "You selected Yes."
Else
MsgBox "You selected No."
End If
End Sub
Use a question-style dialog only when the answer affects what the macro does. For a message that merely reports a variable, an OK button is usually enough. Avoid putting sensitive information in a dialog that could be seen by someone looking at the screen.
Common problems and how to fix them
- The dialog shows a variable’s name or gives an error. Check spelling and make sure the variable has been assigned a value before the
MsgBoxline runs. WithOption Explicit, VBA will flag undeclared names during compilation. - The message contains only a value, with no explanation. Add a quoted label and join it with
&, as inMsgBox "Score: " & score. Keep spaces inside the quoted text where you want them to appear. - Text and a number do not combine as expected. Use
&for joining and, when useful, convert a value withCStr. UseFormat$when you also need control over how a number or date appears. - The message appears as one long line. Insert
vbCrLfbetween the sections that should appear on separate lines. - The macro does not run. Confirm that the code is in a standard module and that macros are permitted for the workbook. If the procedure is not visible in the macro list, check that it is a public, argument-free
Subrather than a function or a procedure that requires arguments.
Another common confusion is expecting MsgBox to print to a worksheet or printer. It does neither: it opens a dialog. To put a value in a worksheet, assign it to a range, such as a cell’s Value property. To inspect a value during development without interrupting the macro, use Debug.Print and view the Immediate window in the Visual Basic Editor.
MsgBox compared with Debug.Print
Use MsgBox when a person running the macro needs to notice information or choose a response. It is visible and straightforward, but it pauses execution until the user dismisses the dialog. That makes repeated message boxes disruptive in a loop or a macro that processes many rows.
Use Debug.Print for temporary diagnostics while writing or troubleshooting code. It sends output to the Immediate window and does not ask the user to click a button. In the Visual Basic Editor, open that window with Ctrl+G on Windows. On Mac, use View > Immediate Window in the editor; shortcuts can vary with keyboard configuration.
For a lasting report, write values to worksheet cells or create an appropriate output file instead of opening one dialog per item. A message box is best for a short status, a warning, or a small result that needs immediate attention—not for a large table of data.
Running macros safely
Before running a macro that changes workbook data, save a separate copy of the workbook. Excel’s Undo command, including Ctrl+Z on Windows, cannot undo actions performed by VBA. This example only reads a cell and displays it, but other macros may overwrite cells, delete content, or change workbook structure.
Run only macros you understand and trust. A macro-enabled workbook can contain code that changes files or performs other actions beyond displaying a message. Review unfamiliar code before allowing it to run, and follow your organization’s macro-security rules. On Windows, you can run a selected procedure from the Visual Basic Editor with F5; you can also use Developer > Macros in Excel. The corresponding menus are available in Excel for Mac, although the interface and shortcuts can differ.
Frequently Asked Questions
Can I put a variable directly in a MsgBox?
Yes. Use MsgBox variableName to display the value on its own. Add a label with MsgBox "Result: " & variableName when readers need context.
Why does MsgBox show a number instead of formatted currency?
A numeric variable stores a value, not necessarily the display format you want. Apply Format$ to the value, then concatenate the resulting text with the label and currency symbol.
How do I show two variables on separate lines?
Join the parts with & and place vbCrLf between them. For example, a prompt can combine a name, a line break, and a count in one MsgBox.
Can MsgBox return the user’s answer?
Yes. Assign the result to a variable, such as one declared As VbMsgBoxResult, and compare it with constants such as vbYes or vbNo. The dialog returns the selected button, not free-form text.
Why use Debug.Print instead of MsgBox?
Use Debug.Print when you want diagnostic output in the Visual Basic Editor’s Immediate window without stopping for a click. Use MsgBox when the person using the workbook needs to see or respond to a pop-up.
Related
- Append Queries in Power Query: How to Combine Tables
- Power Query Editor: What It Is, How It Works, and Why
- Excel Data Validation Icon: What It Looks Like and Does
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- VBA: Filter a PivotTable by Cell Value AutomaticallyTo filter an Excel PivotTable from a cell, use VBA to read that cell and assign its value…
- Excel VBA Loops: How to Repeat Tasks EfficientlyAn Excel VBA loop repeats a block of code until it has processed a set number of items…
- Excel VBA: How to Open a UserFormIn Excel VBA, open a UserForm by calling its Show method from a macro or another procedure. Use…
- Excel VBA: Convert a Variant to a StringIn Excel VBA, use CStr to convert a Variant value to a String: for example, textValue = CStr(value).…
- Excel VBA Copy: How to Copy Cells, Sheets, and FilesTo copy cells with Excel VBA, use Range.Copy with a destination, such as Worksheets("Sales").Range("A1:D20").Copy Destination:=Worksheets("Summary").Range("A1"). This copies the…
- Excel VBA On Error GoTo: How Error Handling WorksIn Excel VBA, On Error GoTo LabelName sends execution to a named error-handling section when a run-time error…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.