VBA course · Lesson 14 of 33
Talking to the user: MsgBox and InputBox
Show messages and ask questions with MsgBox buttons, icons and return values, get input with InputBox and Application.InputBox, pick ranges, handle Cancel.
Most macros need to talk to the person running them at least a little: confirm that a job is finished, warn before deleting data, ask which month to report on, or let the user select the range to process. VBA has two built-in tools for this. MsgBox shows a message and optionally asks a yes/no style question. InputBox asks the user to type a value. Excel adds a third, more powerful one, Application.InputBox, which can check the type of the answer and even let the user click a range on the sheet.
For anything more complex, such as several fields at once, drop-down lists or check boxes, you build a UserForm (UserForms: build a data-entry form in VBA). But for a quick question, these dialogs are perfect.
MsgBox as a statement: just show a message
The simplest form shows text and an OK button:
Option Explicit
Sub ReportDone()
MsgBox "The March sales report has been created."
End SubMsgBox takes up to five arguments, of which you will use the first three: MsgBox prompt, buttons, title. The title replaces the default "Microsoft Excel" in the title bar, and the buttons argument chooses the buttons and the icon. Long messages can be split over several lines with vbCrLf (Working with text (strings) in VBA).
Option Explicit
Sub ImportSummary()
Dim rowsImported As Long
Dim rowsSkipped As Long
rowsImported = 1248
rowsSkipped = 3
MsgBox "Import finished." & vbCrLf & vbCrLf & _
"Rows imported: " & Format(rowsImported, "#,##0") & vbCrLf & _
"Rows skipped: " & rowsSkipped, _
vbInformation, "Sales import"
End SubThe space and underscore _ at the end of a line is the line-continuation character: it lets one long statement continue on the next line. Without brackets around the arguments, this is a statement: you are not interested in which button was pressed.
Buttons and icons
The buttons argument is built by adding constants together, one for the button set and one for the icon:
| Button constant | Buttons shown |
|---|---|
| vbOKOnly | OK (the default) |
| vbOKCancel | OK, Cancel |
| vbYesNo | Yes, No |
| vbYesNoCancel | Yes, No, Cancel |
| vbRetryCancel | Retry, Cancel |
| vbAbortRetryIgnore | Abort, Retry, Ignore |
| Icon constant | Use it for |
|---|---|
| vbInformation | Something finished or for your information |
| vbExclamation | A warning, the user should pay attention |
| vbQuestion | A question (Microsoft now discourages it, but it is still common) |
| vbCritical | An error or a dangerous action |
You can also add vbDefaultButton2 to make the second button the default, the one selected when the user simply presses Enter. For anything destructive, make the safe choice the default.
MsgBox as a function: reading the answer
When you need to know which button the user clicked, use MsgBox as a function: put the arguments in brackets and store the result. The return value is one of these constants: vbOK, vbCancel, vbYes, vbNo, vbRetry, vbAbort, vbIgnore.
Option Explicit
Sub ClearOldData()
Dim answer As VbMsgBoxResult
answer = MsgBox("Delete all rows on the sheet 'Data' and start a new month?" & vbCrLf & _
"This cannot be undone.", _
vbYesNo + vbExclamation + vbDefaultButton2, "Start new month")
If answer = vbYes Then
Worksheets("Data").Range("A2:H10000").ClearContents
MsgBox "Data cleared.", vbInformation
Else
MsgBox "Nothing was changed.", vbInformation
End If
End SubDeclaring answer As VbMsgBoxResult (you could also use Long) gives you IntelliSense for the constants. Because the default is button 2, an accidental Enter chooses No. Remember from What is VBA? Macros, when to use them and macro security that changes made by a macro cannot be undone with Ctrl+Z, so a confirmation like this is good practice before deleting anything.
Select Case reads nicely with three-way answers:
Option Explicit
Sub SaveBeforeClose()
Select Case MsgBox("Save changes to the invoice log?", vbYesNoCancel + vbQuestion, "Invoice log")
Case vbYes
ThisWorkbook.Save
MsgBox "Saved."
Case vbNo
MsgBox "Closing without saving."
Case vbCancel
Exit Sub
End Select
End SubInputBox: asking for a value
The VBA InputBox function shows a prompt with a text box and returns what was typed, always as a String:
Option Explicit
Sub AskCustomer()
Dim customer As String
customer = InputBox("Which customer should the report show?", "Customer report", "Harbor Foods")
If customer = "" Then
MsgBox "No customer entered. The report was not created."
Exit Sub
End If
Range("B1").Value = customer
MsgBox "Report filter set to " & customer
End SubThe third argument is the default text, pre-filled and selected so the user can accept it with Enter. The big weakness of the VBA InputBox is that pressing Cancel and clicking OK with an empty box both return ""; you cannot tell them apart. (Technically StrPtr(answer) = 0 detects Cancel on Windows, but it is an obscure trick and not something to rely on in shared code.) For most purposes, treating an empty answer as "cancel" is fine.
Validating typed input in a loop
Users mistype. If you need a number, check the answer and ask again until it makes sense, giving the user a way out:
Option Explicit
Sub ApplyDiscount()
Dim answer As String
Dim discount As Double
Do
answer = InputBox("Discount in percent (0 to 30):", "Apply discount", "10")
If answer = "" Then Exit Sub ' user cancelled
If IsNumeric(answer) Then
discount = CDbl(answer)
If discount >= 0 And discount <= 30 Then Exit Do
End If
MsgBox "Please type a number between 0 and 30.", vbExclamation
Loop
Range("D2").Value = discount / 100
Range("D2").NumberFormat = "0%"
End SubThis uses the bottom-exit pattern from Do loops: Do While, Do Until and Exit Do: the loop only ends with Exit Do once the answer is valid, or Exit Sub when the user gives up. IsNumeric follows the regional decimal separator, so "7,5" is accepted on a German PC and "7.5" on a UK one.
Application.InputBox: typed answers and range picking
Excel's own Application.InputBox method looks similar but has a crucial extra argument, Type, which tells Excel what kind of answer is allowed. Excel then validates the input itself and shows its own error if the user types the wrong thing.
| Type | Accepts |
|---|---|
| 0 | A formula |
| 1 | A number |
| 2 | Text |
| 4 | A logical value (TRUE/FALSE) |
| 8 | A cell reference (returns a Range object) |
| 16 | An error value |
| 64 | An array of values |
You can add values to allow several types, for example 1 + 2 for a number or text. When the user clicks Cancel, Application.InputBox returns the Boolean False, which you can tell apart from a real answer. That is why the result is usually stored in a Variant:
Option Explicit
Sub AskTarget()
Dim result As Variant
result = Application.InputBox(Prompt:="Monthly sales target:", Title:="Target", _
Default:=50000, Type:=1)
If VarType(result) = vbBoolean Then
MsgBox "Cancelled."
Exit Sub
End If
Range("B1").Value = result
End SubVarType(result) = vbBoolean is a safer cancel test than result = False, because a number 0 would also compare equal to False.
Letting the user select a range (Type:=8)
With Type:=8, the dialog stays open while the user clicks or drags on the sheet, and the address appears in the box. The method returns a Range object, so you must use Set. On Cancel it returns False, and assigning False to a Range variable with Set causes an error, so wrap the call in a small error trap (Error handling and debugging in VBA explains On Error fully):
Option Explicit
Sub RoundSelectedPrices()
Dim target As Range
Dim cell As Range
On Error Resume Next
Set target = Application.InputBox(Prompt:="Select the prices to round to 2 decimals:", _
Title:="Round prices", Default:=Selection.Address, Type:=8)
On Error GoTo 0
If target Is Nothing Then Exit Sub ' Cancel was pressed
For Each cell In target.Cells
If IsNumeric(cell.Value) And Not IsEmpty(cell.Value) Then
cell.Value = Round(cell.Value, 2)
End If
Next cell
MsgBox target.Cells.Count & " cells checked.", vbInformation
End Sub| A | B | |
|---|---|---|
| 1 | Product | Price |
| 2 | Keyboard | 24.987 |
| 3 | Mouse | 12.4449 |
| 4 | Monitor | 189.996 |
| 5 | Cable | 4.1 |
Before: the user selects B2:B5 in the dialog
| A | B | |
|---|---|---|
| 1 | Product | Price |
| 2 | Keyboard | 24.99 |
| 3 | Mouse | 12.44 |
| 4 | Monitor | 190 |
| 5 | Cable | 4.1 |
After RoundSelectedPrices (shown with the General format)
The default Selection.Address pre-fills whatever the user had selected, so they can just press Enter. The user can even switch to another sheet while the dialog is open; the returned range then belongs to that sheet.
Round uses banker's rounding (2.5 becomes 2), unlike the worksheet ROUND (2.5 becomes 3). If you need the same result as the sheet, use Application.WorksheetFunction.Round (see Using Excel worksheet functions in VBA).On a Mac
Both MsgBox and both input boxes work in Excel for Mac, but the dialogs use the Mac look, and some icons are not shown the way they are on Windows. Range picking with Type:=8 works, though selecting on another sheet is less smooth. The vbMsgBoxHelpButton and help-file arguments are ignored.
Good dialog manners
- Keep messages short and specific: "3 invoices could not be found: INV-1042, INV-1051, INV-1077" beats "Error!".
- Use a title so the user knows which macro is speaking.
- Do not show a message inside a loop. A
MsgBoxthat pops up 500 times is a disaster; collect the problems in a string and show them once at the end. - Make the safe button the default for destructive actions.
- Remember that message boxes pause the macro until clicked, which makes them unusable for macros that run unattended. For your own debugging, prefer
Debug.Print.
Common mistakes
- Brackets without storing the result:
MsgBox("Done")on its own line happens to work, butMsgBox("Done", vbInformation)on its own line gives the compile error "Expected: =". Use brackets only when you assign or test the return value. - Adding numbers from
InputBox: the result is text, soInputBox(...) + 10may join instead of add. Convert withCDblafter checkingIsNumeric. - Forgetting
SetwithType:=8. - Testing
result = Falsewhen 0 is a valid answer. - Confusing the two InputBoxes:
InputBox(VBA, noType) versusApplication.InputBox(Excel, withType).
Check yourself
1. Which MsgBox call makes "No" the button chosen when the user presses Enter?
vbDefaultButton2 makes the second button (No) the default.
2. What does the VBA InputBox function return when the user clicks Cancel?
VBA's InputBox returns "", the same as an empty OK, so the two cannot easily be told apart.
3. Which Type value makes Application.InputBox return a Range the user selects?
Type 8 means a cell reference, returned as a Range object that must be assigned with Set.
4. What does Application.InputBox return when the user cancels?
That is why the result is usually stored in a Variant and checked with VarType.
5. Where should you show a MsgBox when a loop finds problems in 200 rows?
Collect the messages in a string and show one summary at the end.