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 " &.
Give MsgBox buttons and it asks a question. MsgBox( 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.
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
InputBox( 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.
Sub SetRate() Dim rate As Variantrate = Application.InputBox( "EUR to USD rate for this month:", Type:=1) If rate = False Then Exit SubRange("B1"). Value = rate End Sub
Common mistakes
MsgBox "Cleared n rows". Inside the quotes, n is just the letter n. Join the variable in with&."Cleared " +. Withn + " rows" +, 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
MsgBoxtells; withvbYesNoit asks, and returnsvbYesorvbNo.- Ask before a step that can't be undone, and
Exit Subon No. InputBoxreturns""on Cancel, andApplication.InputBoxreturns False; check before you use the answer.
Practice
Premium4 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.
Have one? Sign in