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.
Ravindra Bagale's Tip – मराठी
InputBox मध्ये user ने Cancel दाबलं तर रिकामा text येतो, आणि बऱ्याच students चा macro रिकाम्या city साठी report बनवतो किंवा error देतो. InputBox नंतर नेहमी If city = "" Then Exit Sub असा check लिहा. Number हवा असेल तर Application.InputBox Type:=1 वापरा – मग Excel स्वतः validation करतो.
Ravindra Bagale's Tip – हिंदी
InputBox में user ने Cancel दबाया तो खाली text आता है, और बहुत से students का macro खाली city के लिए report बना देता है या error देता है. InputBox के बाद हमेशा If city = "" Then Exit Sub जैसा check लिखो. Number चाहिए तो Application.InputBox Type:=1 इस्तेमाल करो – फिर Excel खुद validation करता है.
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.