Skip to content

Ask and confirm with MsgBox and InputBox

Dialogs, functions and events9 minPremium

Builds on Make decisions with If and Select Case.

A project coordinator at an engineering firm in Eindhoven runs a macro every Monday that clears last week's hours from the team timesheet. Last month someone ran it on a Friday by mistake. One question before it clears anything would have saved an afternoon of retyping.

How it works

MsgBox "Text" shows a message with an OK button. Join text and values with &, as in MsgBox "Cleared " & n & " rows".

Give MsgBox buttons and it asks a question. MsgBox("Clear last week's hours?", vbYesNo + vbQuestion) shows Yes and No with a question mark, and returns vbYes or vbNo. Test the answer with If, and leave with Exit Sub on No.

VBA
Sub ClearTimesheet()
If MsgBox("Clear last week's hours?", vbYesNo + vbQuestion) = vbNo Then Exit Sub
Range("C2:G40").ClearContents
MsgBox "Last week's hours are cleared."
End Sub
Asks before clearing last week's hours, stops on No, and says when it's done.

InputBox("Exchange rate for this month:") shows a box to type in and returns what was typed, as text. If the person selects Cancel, or OK with the box empty, it returns an empty string, "". Check for that before you use the answer.

Application.InputBox is Excel's own version. Its Type argument says what to accept: 1 for a number, 2 for text, 8 for cells the person selects. Excel checks the entry for you, and Cancel returns False.

VBA
Sub SetRate()
Dim rate As Variant
rate = Application.InputBox("EUR to USD rate for this month:", Type:=1)
If rate = False Then Exit Sub
Range("B1").Value = rate
End Sub
Asks for this month's rate as a number, and stops if the person cancels.

Common mistakes

  • MsgBox "Cleared n rows". Inside the quotes, n is just the letter n. Join the variable in with &.
  • "Cleared " + n + " rows". With +, VBA tries to add the text to the number and stops with "Type mismatch". Join text with &.
  • Using an InputBox answer without checking it. A Cancel gives "", and turning that into a number stops the macro.

In short

  • MsgBox tells; with vbYesNo it asks, and returns vbYes or vbNo.
  • Ask before a step that can't be undone, and Exit Sub on No.
  • InputBox returns "" on Cancel, and Application.InputBox returns False; check before you use the answer.

Practice

Premium

4 exercises: 3 macros and 1 quiz question.

Practice is part of Premium

Every lesson is free to read, and you can practice the free lessons without an account. This lesson's exercises are part of Premium, which you add to a free account.