12.8 MsgBox and InputBox
Rohan wants Excel to ask which city should be prepared for tomorrow's dispatch. The action needs a way to stop if the operator changes their mind. A different prompt asks for a target number of orders, where zero is a real value. This lesson separates the typed answer, the validation result and the final permission to write.
Read a choice and confirm a specific action
Give each dialog one job
Imagine a fictional Swiggy-style dispatch desk. The location labels, quantities and workbook actions here are practice data. On a small Setup sheet, the first procedure writes a selected city to E2. The second procedure writes a planned order target to E4. Both are choices made by a person while working in desktop Excel. Changing either choice replaces a single previously recorded value. The workbook should keep the previous choice when the person presses Cancel.
- Information message: A MsgBox can display one message with an acknowledgement button. Use it to show a result or a useful next step. The return from a one-button message usually does not need to decide anything in your procedure.
- Confirmation message: MsgBox also supports a group of buttons. If the code captures its return value, you can distinguish the operator's choice using named constants. For an action that replaces a stored value, describe the cell and new value and require the appropriate positive choice.
- Text response: VBA's InputBox function displays a prompt, allows a default and returns a String. Cancel produces an empty string, as can choosing OK with nothing in the field. You can design your exercise to treat either as “leave the existing value in place.” If your workflow needs to distinguish them, this function alone cannot provide that distinction.
- Typed response: Excel's Application.InputBox is a different method. It accepts a Type argument. Type 1 requests a number. Type 8 returns a Range object when successfully selecting a worksheet range. Its Cancel path returns Boolean False. Read the documentation and handle the chosen type before converting it or assigning it to another variable.
Read a message with both buttons and return values in mind
| Configuration | Buttons | Return to check |
|---|---|---|
| vbOKOnly | OK | vbOK |
| vbOKCancel | OK or Cancel | vbOK or vbCancel |
| vbYesNo | Yes or No | vbYes or vbNo |
| vbYesNoCancel | Yes, No or Cancel | vbYes, vbNo or vbCancel |
You can combine one button group with options such as an icon and default button. In the exercise vbYesNoCancel Or vbQuestion Or vbDefaultButton2 provides three choices with the second as the default. The icon describes the type of prompt to a reader. It does not itself cause an error or grant permission. Keep the question and default choice aligned with the desired decision. Read the different return constants rather than comparing whatever number you saw the first time.
Remember: Cancel, blank text, a rejected input and an approved zero can each look like “nothing happened.” Decide which one the operator actually chose before writing a value.
Design the prompt from the allowed input
Tell the operator what an acceptable answer looks like
A usable input phrase says what to enter, gives the permitted choices and names the unit when there is one. “Enter target” could mean rupees, items or orders. In this exercise we ask for a whole order count from zero through five thousand. We ask for just two known city labels. The confirmation messages name the exact choice and what will be replaced. A colleague can then choose No without having to guess which worksheet cell was affected.
- Use a suggestion on purpose. The current exercise city defaults to Pune in the prompt. That can be convenient for a repeated run. It is not confirmation and does not force the person to accept the result. If you offer a default for a target amount, make it visible and revisit whether the previous target is still relevant.
- Normalize before testing. Trim removes ordinary leading and trailing spaces in the city input. A case-insensitive comparison can accept Pune and PUNE as the same permitted label. The code stores one canonical spelling taken from the allowed choices, so a report user sees consistent results.
- Use bounds in addition to type. Excel can restrict one prompt to numbers, but the business can require a whole count within a much smaller range. The procedure checks those limits before writing. A value of four and a half can be a valid number while still being an invalid order target.
- Make positive confirmation precise. If the operator chooses Yes or OK, the routine can write its reserved cell. Every other choice exits before the assignment. This narrow condition is easier to verify than writing first and trying to undo on a negative response.
Choose interactive procedures for interactive jobs
A person is present for these VBA exercises. A prompt waits for their response, then the procedure continues. An unattended scheduled job generally needs its inputs from explicit configuration, validation and a run report instead of a dialog awaiting a click. Later lessons compare Office Scripts and cloud flows with desktop VBA. Here the two environments should not be mixed: create and run the workbook macro only in authorized desktop Excel, where the operator can see the dialog and make the decision.
Lab one. Ask for a city and confirm the stored choice
Make the effect small enough to inspect
Create a disposable PromptPractice.xlsm workbook in approved desktop Excel. Make a worksheet called Setup. Use D2 for the label Selected city, E2 for its value, D4 for the label Target orders and E4 for its value. Start E2 at Nashik and E4 at 12. In H2 put “Keep this setup note.” The two macros in these labs have distinct write scopes. Read the original values and the note before modifying the workbook.
| Cell | Initial value | Affected by |
|---|---|---|
| E2 | Nashik | City prompt only |
| E4 | 12 | Target prompt only |
| H2 | Keep this setup note | Neither action |
In the VBA project's standard module enter the code. It takes the city from a string question, trims ordinary spaces and checks whether it matches the permitted set. The procedure uses the current code workbook and Setup worksheet. It performs no work for pending input or any response other than Yes. The message describes a replacement of the selected city, which is the task this sample actually completes.
Option Explicit
Public Sub ChooseReportCity()
Dim ws As Worksheet
Dim city As String
Dim answer As VbMsgBoxResult
Set ws = ThisWorkbook.Worksheets("Setup")
city = Trim$(VBA.InputBox("Enter Pune or Nashik:", "Dispatch City", "Pune"))
If Len(city) = 0 Then Exit Sub
If StrComp(city, "Pune", vbTextCompare) = 0 Then
city = "Pune"
ElseIf StrComp(city, "Nashik", vbTextCompare) = 0 Then
city = "Nashik"
Else
MsgBox "Use Pune or Nashik.", vbExclamation, "City Required"
Exit Sub
End If
answer = MsgBox("Save " & city & " as the selected city in Setup E2?", _
vbYesNoCancel Or vbQuestion Or vbDefaultButton2, _
"Confirm Selected City")
If answer <> vbYes Then Exit Sub
ws.Range("E2").Value2 = city
MsgBox "Setup E2 now stores " & city & ".", vbInformation
End Sub
- Trim and test text: With the sample pune , ordinary surrounding spaces can be removed. Case-insensitive comparison returns equality for Pune. The code writes the approved label Pune, keeping consistent reporting categories. A blank response after trimming goes straight to Exit Sub.
- Require one allowed label: The known cities are verified before showing the confirmation. A value such as Mumbai, a star character or two city names entered together cannot pass. It produces the short explanatory message and leaves both destination fields as they were.
- Capture the confirmation: Store the selected response in a VbMsgBoxResult. One of vbYes, vbNo or vbCancel describes the outcome. Use the named return constants to control which path reaches the assignment.
- Report the actual effect: The last message describes E2 after that one write. It does not promise that a full city report was created. A real multi-step report would also need its own separate checklist of output row counts or totals.
Exercise each exit path before accepting a replacement
- Run ChooseReportCity in the named workbook. Press Cancel in the first dialog. Expect no confirmation message and no cell changes. Try again with all text removed and press OK. This procedure treats both responses as “no change.” E2 remains Nashik.
- Try a city outside the practice list. Check for the message asking for Pune or Nashik, then return to Setup. Nashik should still be there. A cancelled or invalid input can both leave the same cell contents. The prompts you saw distinguish the paths.
- Enter Pune, then choose No in the confirmation. E2 should stay Nashik. Try another run and choose Cancel in the confirmation. The procedure ends with the same stored state. Test both paths separately so a later edit cannot accidentally change one of them.
- Enter lowercase pune with surrounding ordinary spaces and choose Yes. The stored city becomes Pune. Check E2 directly and compare E4 and H2. Only E2 changes. The result should show the canonical spelling independent of the typed case.
- Save or reset the copy under your practice rules. If you can read the code but cannot run desktop VBA, make a three-column paper table containing typed response, button result and observed or predicted E2. Both the rejection and approval checks can be reasoned about without modifying a workbook.
Lab two. Save a valid zero without confusing it with Cancel
Type-check the answer before comparing numbers
Use the same Setup sheet, with the starting target E4 set to 12. An operator can set zero if there is deliberately no planned delivery work. Pressing Cancel means “keep my last target.” Those commands have different results even if a careless VBA comparison treats a numeric zero and Boolean False as equivalent. Save the immediate result as a Variant and inspect which kind of value came back. Only then convert a known numeric response.
Public Sub SetDispatchTarget()
Dim ws As Worksheet
Dim response As Variant
Dim target As Double
Dim answer As VbMsgBoxResult
Set ws = ThisWorkbook.Worksheets("Setup")
response = Application.InputBox( _
Prompt:="Enter a whole order target from 0 to 5000:", _
Title:="Dispatch Target", Type:=1)
If VarType(response) = vbBoolean Then Exit Sub
target = CDbl(response)
If target < 0 Or target > 5000 Or target <> Fix(target) Then
MsgBox "Use a whole number from 0 to 5000.", vbExclamation
Exit Sub
End If
answer = MsgBox("Replace Setup E4 with " & target & " orders?", _
vbOKCancel Or vbQuestion Or vbDefaultButton2, _
"Confirm Target")
If answer <> vbOK Then Exit Sub
ws.Range("E4").Value2 = CLng(target)
MsgBox "Target saved.", vbInformation
End Sub
- Call the Excel method:
Application.InputBoxasks Excel for the numeric response when Type is 1. Excel performs its own numeric entry validation at that dialog. The procedure can focus on the supported return values, the numeric limits and the cancel case, rather than treating any text as a number. - Keep the type information: A Variant can hold either the numeric response or a Boolean. Assigning the response directly to a Long first could coerce a Cancel value and remove the distinction you need. After the first guard, the procedure works with the actual number.
- Validate the whole-count rule: Compare the number to its integer part with Fix. A fractional number passes Excel's prompt but fails this quantity rule. Test bounds before using the allowed whole value. For this range of possible inputs, CLng can store the accepted target.
- Give the operator a final checkpoint: The code shows the selected target and asks whether to replace E4. If Cancel is chosen at this point, the procedure still leaves the old value alone. At the first prompt Cancel returns a Boolean; at the second it returns a MsgBox result. Match the return convention to the function you called.
Run the target prompt with controlled inputs
Distinguish accepting zero from keeping the previous target
The two choices can appear equivalent only when the old target was already zero. Begin at 12 each time you need to prove the difference. This makes a successful rewrite to zero visible. For a negative or cancelled choice, keep the old nonzero value as a marker. Use the workbook-scoped Macros dialog and check the result on the Setup worksheet after closing each prompt.
- Cancel at the number prompt. Open SetDispatchTarget and press Cancel before entering anything. The return for this method is Boolean False, so the procedure ends before trying to convert it. E4 remains 12 and there is no second prompt. Confirm that E2 and H2 also remain unchanged.
- Enter zero and approve it. Restore the initial state if needed. Type the number 0 and accept the number input. In the confirmation choose OK when it asks to replace E4 with zero. The final message appears. E4 now stores a numeric zero. In an unused check cell you can use the formula below to verify it is a number. Choose a General format if you want the zero visible on screen.
- Enter zero and decline the replacement. Reset E4 to 12. Accept the numeric zero at the first prompt, then pick Cancel at the confirmation. There is no success message. E4 stays 12. This time the numeric test succeeded, so the second prompt waiting for the operator was expected.
- Enter a fraction. Try 4.5 using your system's decimal separator. Excel may accept it as a number at the first dialog. The exercise's whole-number rule rejects it with a specific message before confirmation. E4 stays 12. Inspect the line using Fix and verify why the values differ.
- Compare a boundary and the next value. Try 5000 and choose OK in the confirmation. E4 can become 5000. Reset the cell, then try 5001. It fails the upper bound and does not change the workbook. A negative number also fails before confirmation. These tests show that the numeric dialog and business rules perform separate checks.
- Try nonnumeric words. At the first prompt type an ordinary word such as many. The Excel number selector is expected to reject that as a numeric entry. Do not treat its feedback as a message shown by the later business rule. Cancel the prompt or replace the word with a number, then observe what gets to the next branch.
=ISNUMBER(E4)
| First interaction | Confirmation | Final E4 |
|---|---|---|
| Cancel numeric prompt | No confirmation | 12 |
| Number 0 | OK | 0 |
| Number 0 | Cancel | 12 |
| Number 4.5 | Rejected before confirmation | 12 |
| Number 5000 | OK | 5000 |
| Number 5001 | Rejected before confirmation | 12 |
| Number -1 | Rejected before confirmation | 12 |
Read this path one decision at a time
Trace a new target without losing the old choice
Current target
Setup E4 starts at 12. The macro is allowed to replace this value only after a typed valid input and an approved confirmation.
Read the prompt response
Cancel returns Boolean False and stops. Typed zero returns a number and proceeds to a separate range check.
Validate and ask again
Zero is an allowed whole number. Verify that the confirmation shows the requested result. Cancel here leaves E4 at 12.
Commit and inspect
With OK from the confirmation, write the number 0 and confirm E4 changed. Check that the selected city and note are intact.
This stepper is a diagram of one invocation. Another run starts using the current value after the previous operation. For example after storing 5000, cancelling a new prompt keeps 5000. The scratch table assumes you reset to 12 for each observation. Recording the initial state in a lab prevents you from misreading a correct preservation behavior as an incorrect result.
Keep response types visible in the program
Inspect a response before any conversion
The language name InputBox can refer to the VBA function or, with Application before it, the Excel method. Their prompts may resemble each other. The return contracts differ. The plain VBA function returns a String, including an empty string when the user cancels. It is suitable for the case where blank and cancel both mean leave the city unchanged. The Excel method with Type 1 returns a numeric choice or the Boolean cancellation marker. Keep these two calls distinct when you look up examples.
- Response in a Variant: A Variant preserves a Number or Boolean as its original subtype. VarType first inspects that subtype. In our method's numeric-only form, a Boolean response identifies Cancel. The question was asking for a number, so a user typing zero does not return the Boolean cancellation marker.
- Do the numeric conversion after the first branch: CDbl asks VBA to produce a Double from the known numeric response. We compare it with its whole part and with the allowed bounds before choosing a Long for the destination. Converting to Long first can round a fraction and conceal an invalid request.
- Accept range input only when the job requires it: A different configuration with Type 8 can return a Range object. An object assignment uses Set, and the Boolean cancellation path still needs care. A worksheet range may represent another sheet or a larger selection than you expect. Validate worksheet ownership and dimensions before any future code edits it. A separate range-selection routine should have dedicated tests.
- Limit the choices to what is helpful: Excel Application.InputBox supports other Type values, such as a text request or a logical request. If your prompt allowed actual Boolean values as data, checking only whether the response is Boolean would no longer uniquely identify Cancel. The guard in this exercise specifically matches Type 1. Build a new outcome table before permitting different responses.
Keep long helper text on the worksheet
The prompt itself should be short and clear. For the Excel method, Microsoft documents a maximum prompt length of 255 characters; a longer string can return an error instead of displaying the expected dialog. Keep detailed instructions on the Setup sheet and collect only necessary input in the message. This avoids repeating an entire report explanation every time the person needs to set one target. The short prompts here also keep error branches and positive branches easier to find.
A confirmation message can restate the normalized value without repeating every character the user entered. If they typed their city as “ pUnE ” and see “Save Pune as the selected city in Setup E2?”, they get an immediate chance to review the result before it is stored. When the exact original spelling has a business meaning, such as a legal name or the text of an ID, decide which transformations are appropriate for that field. For this training city's grouping label, canonical spelling helps keep reports consistent.
Validate the result against a separate worksheet calculation
Choose a visible difference for the test
On a separate practice copy make G4 the open-order count for the local dispatch. Use a fixed example of eight. Reserve G6 for a simple calculation that compares the chosen target E4 with that count. This is only a way to see the effect of changing the target in the exercise. It does not create or move an actual order. Type the check below and name it “Target less open orders.” In this example it gives four when the target is 12 and minus eight when the target is zero.
G6: =E4-G4
- Valid numeric zero: E4 becomes 0 only when the final confirmation returns OK. In the ordinary automatically calculating workbook, G6 now reads minus eight. The two cells together prove both the saved value and the new arithmetic difference caused by it.
- Cancel at the first prompt: Reset E4 to 12 and try again. The worksheet continues to show four in G6. No final confirmation appeared because the procedure exited before any write. Compare it with the numeric zero run beginning at the same state.
- Cancel after a valid number: Enter 16, accept the numeric dialog and cancel the confirmation. The new requested difference would have been eight, but E4 remains 12 and the formula still reports four. Distinguish the two kinds of cancellation by whether the confirmation was displayed.
- Vary the current state: Begin once at 16. Cancel and expect the stored count to stay at 16. Using multiple values proves Cancel preserves what was already there. Beginning always at a single value could hide a routine that accidentally writes that same constant on a negative response.
Inspect how a rejected city affects a worksheet
One route supervisor wants an allowed city and expects its display label to stay consistent. In this exercise E2 can be used in a separate formula to pick the corresponding name for a heading. You can check the effect simply by referring to E2 in an unused cell. Type “ pUne ” and reject at the confirmation. The old worksheet title based on Nashik stays. Approve the same normalized input in a separate run. Now the dependent heading spells Pune exactly. These checks separate parsing of the entered input from a deliberately approved write.
If the allowed set grows from two cities to twenty, you would normally keep a validated list of city names and give users a choice instead of requiring exact spelling from memory. A drop-down on an input cell is suitable when the workbook already has a visible input area and can respond through formulas. A VBA prompt can add a deliberate confirmation for a small workbook action and can guide a person through the steps one at a time. Decide what happens when a selection is blank in whichever interface you use.
Find the step that stopped the run
Use the message and the output together
- The dialog appears but never accepts words. The numeric test uses Application.InputBox with Type 1. Think about whether the operator is answering the right question and using a local numeric entry format. If the input should be a city, call the separate command designed for a text response. Treat data roles as distinct before weakening a validation check.
- The number was accepted but the write did not occur. It may be outside the allowed interval or have a fractional part. Read the value and rule, then see whether the final confirmation displayed. If you selected Cancel there, no write is the intended outcome. Try one valid amount with a clearly reset starting state to prove the positive branch.
- Cancel appears to have written a zero. Check how the initial return is stored. If the code immediately assigns the response to a numeric variable or compares it directly with False, the type distinction can be lost. In this lesson store the result in a Variant and inspect VarType before conversion. Test both a previous nonzero followed by Cancel and a separate approved zero.
- The city changed when the operator intended No. Look for the first assignment to E2 and confirm that it appears after the exact Yes guard. If the assignment precedes the confirmation or runs in the wrong branch, you have a code issue. Use an isolated copy with an earlier city to catch the incorrect write. Keep every other choice outside the positive write condition.
- The correct response appears in a message but the requested cell did not update. Check the actual workbook and worksheet. The Setup sheet belongs to the workbook containing the module. Also inspect whether the result cell is protected or belongs to another report layout. A confirmation can express intent without establishing the write succeeded. Verify the final cell after an approved run.
Decide whether two prompts are one operation or separate ones
Suppose a learner approves Pune in the city procedure, then starts the numeric procedure and cancels after reading the target. The final worksheet should contain Pune and the previous target. The actions have separate saved destinations and the first confirmation already authorized the city write. A Cancel in the second procedure affects its own execution. It does not undo a completed write from an earlier procedure. Test this sequence in the practice workbook so you can explain the visible pair of values after the second prompt closes.
Now imagine a team wants a new city and target to be accepted together as one decision. They could first collect both values, keep them in variables, validate both and show one confirmation naming both cells and contents. Then a cancelled target should leave the old city too, because the routine would not write either before validating and confirming. This is a different workflow contract. The existing two commands do not make that guarantee. If you build a combined version in a later project, test each individual cancellation path, one known successful pair and whether a failed worksheet write can leave a partial update.
Mock the combined workflow on paper with the actual lab values. Start with Nashik and 12, type Pune and then give a fractional target of 1.5. Your proposed combined procedure should reject the second input and still show Nashik and 12. Next choose Pune and an explicit zero, approve the final pair and expect Pune and 0. Label those states as intended behavior for the proposed combined workflow. Keep today's tested commands and their individual acceptance cases separate. This helps a reviewer know which runs they can reproduce directly and which rules belong to a future exercise.
Document the job so an operator can repeat it
Say which command to start, what form the answer takes, and what changes after confirmation. For example, “On the copy with a target of 12, run SetDispatchTarget. Choose zero at the numeric prompt and OK at the confirmation. Expect E4 to store zero and keep H2.” Pair that with an explicit negative test. In a second run using the same starting state, Cancel at either stage and see 12. A note should identify the test workbook and time, because a screenshot of the number alone says little about which branch was exercised. Start with a different value when you need a visible before-and-after result.
Keep the exercise message short enough to read each time you run it. If operations depend on approved values from two different people, give both of them a clear worksheet field and describe the sequence for both decisions. A dialog's Yes cannot replace a separate approval process or check the authority of the person clicking. In this lab it only means the current operator accepted the displayed replacement in the copied test workbook.
Trace two cases: Begin with 12. Outline the result when zero is approved, and then outline the result when the second message is cancelled. Include what type each first prompt returned and whether the destination assignment ran.
Quick checks
Identify the response and the resulting write
What does a cancelled VBA.InputBox return?
It returns an empty String. Pressing OK with no text can give the same result. The city procedure treats both as a choice to leave E2 alone. If a future process needs different behavior for the two outcomes, choose a suitable different input interface and test both cases.
What happens after the user enters “ pUne ” and selects No?
The code trims ordinary spaces and matches the label using a case-insensitive test. That produces the proposed value Pune. The No response exits before writing. If Setup E2 started at Nashik, it stays Nashik. A correctly parsed choice does not necessarily mean the person approved the change.
Which return type identifies cancellation for Application.InputBox with Type 1?
The Cancel path returns Boolean False. The prompt otherwise requests a numeric value. Store the result in a Variant and inspect VarType before converting it. Keeping the type lets the procedure distinguish a valid numeric zero from the user's request to stop.
Why can a numeric prompt accept an amount that the order procedure rejects?
The prompt asks Excel for a number, so several numeric formats can pass. The order procedure checks an additional rule: a whole number from 0 through 5000. Values like 4.5 and 5001 are numbers that fail that rule. The procedure returns before confirmation and does not change the stored target.
Which result tells a VBA MsgBox whether the user gave permission?
Capture the chosen button with the function return. For the city routine only vbYes leads to the assignment. For the target routine only vbOK leads to the assignment. The question icon and default button influence the interaction but are not the selected answer.
What does the read-only worksheet check show after saving zero with eight open orders?
E4 contains the number zero and the independent difference in G6 is minus eight. Cancelling from the same starting value of twelve preserves twelve and four. Checking both cells makes the difference observable without relying solely on a dialog message.
Interview and discussion
Explain how you build an interactive input contract
How would you design a numeric input that accepts zero but treats Cancel as no change?
Use the typed Excel input method with Type 1, hold its return in a Variant, inspect for the documented Boolean cancellation before conversion, then validate the numeric value. Prompt for confirmation if the change replaces an existing result. Test a numeric zero and Cancel from the same nonzero starting value so they can be distinguished.
What qualities make a useful confirmation message?
Name the action, the item affected and the proposed value. In this example the message gives the exact Setup cell and the city or count. Use a clear button group appropriate to the decision and choose a sensible default. Require the positive return before changing the workbook.
Why would you avoid forcing a new default value whenever input is blank?
Blank or Cancel may express a request to retain a validated earlier value. Writing a new default would silently change the outcome. Show a possible default in the prompt where appropriate, and update the sheet only when the operator explicitly provides a valid response and approves the final action.
Would you use these dialogs in an unattended run?
They wait for a person to respond, so this design fits an interactive desktop workflow. An unattended process instead needs an explicit configuration source and a way to report invalid data or ask for action outside its workbook routine. Validate those inputs before starting any writes and record exactly what happened when no valid value is available.
How do you prove a negative choice left the previous state intact?
Start with a recorded nonzero target or differently spelled valid city. Exercise Cancel, No or invalid input one at a time. Read the exact output and an adjacent marker. Repeat with a different initial value if necessary. This distinguishes preserving the previous state from accidentally assigning an output that just happens to match it.
Six recall cards
- Text input
VBA.InputBox returns a String. Blank and Cancel can both give empty text. Decide how your task treats that result.
- Numeric input
Application.InputBox Type 1 asks for a number. Store the response in a Variant before inspecting its type.
- Zero is valid here
A numeric zero may become the saved target, while Boolean False indicates cancellation of the number prompt.
- Positive confirmation
Only the selected affirmative response reaches the write. For these labs use vbYes for city and vbOK for target.
- Validate separately
A numeric type can still fail a count, limit or whole-number rule. Check first and convert second.
- Proof of write
Read the named cell and one unrelated marker. Note whether a confirmation and success message actually appeared.
Microsoft references
Continue practising: explore the existing Excel Task Hub for additional exercises.