Ravindra BagaleCourses & study guides

12. Macros and VBA

12.8 MsgBox and InputBox

Sub AskCity()
    Dim city As String
    Dim answer As VbMsgBoxResult

    city = InputBox("Enter city name (e.g. Pune):", "Blinkit Report", "Pune")
    If city = "" Then Exit Sub        ' user pressed Cancel or left it empty

    answer = MsgBox("Create report for " & city & "?", vbYesNo + vbQuestion, "Confirm")
    If answer = vbYes Then
        MsgBox "Report for " & city & " will be created.", vbInformation
    Else
        MsgBox "Cancelled.", vbExclamation
    End If
End Sub
Constant Effect
vbOKOnly, vbYesNo, vbYesNoCancel, vbOKCancel Buttons
vbInformation, vbQuestion, vbExclamation, vbCritical Icon
Return values vbYes, vbNo, vbCancel, vbOK Which button was clicked

For numbers or ranges use Application.InputBox: qty = Application.InputBox("Enter target orders", Type:=1) (Type 1 = number; Type 8 = a range the user selects).

Ravindra Bagale's Tip

If the user clicks Cancel in an InputBox, you get empty text, and many students' macros build a report for an empty city or throw an error. After an InputBox, always write a check like If city = "" Then Exit Sub. If you need a number, use Application.InputBox Type:=1 – then Excel does the validation itself.

Practice task

Ask the user for a minimum amount with Application.InputBox (Type 1) and show how many orders are above it in a MsgBox with the Information icon.