I have an input box asking user to enter a date. How do I let the program know to stop if the user click cancel or close the input dialog instead of press okay.
Something like if str=vbCancel then exit sub
Currently, user can hit OK or Cancel but the program still runs
str = InputBox(Prompt:="Enter Date MM/DD/YYY", _ Title:="Date Confirmation", Default:=Date)
The easiest and most effective way that I have found to handle the siutation where a user clicks the InputBox Function's Cancel button is to use the StrPtr Function to identify when the Cancel button has been clicked.
How to use Input Box in a VBA Code. Type “InputBox” and enter a space and you will get a tool for the arguments you need to define. Specify the “Prompt”, message that you want to show to the user. Define a title for the input box, otherwise, it will show the default title.
The InputBox function prompts the users to enter values. After entering the values, if the user clicks the OK button or presses ENTER on the keyboard, the InputBox function will return the text in the text box.
If the user clicks Cancel, a zero-length string is returned. You can't differentiate this from entering an empty string. You can however make your own custom InputBox class...
EDIT to properly differentiate between empty string and cancel, according to this answer.
Your example
Private Sub test() Dim result As String result = InputBox("Enter Date MM/DD/YYY", "Date Confirmation", Now) If StrPtr(result) = 0 Then MsgBox ("User canceled!") ElseIf result = vbNullString Then MsgBox ("User didn't enter anything!") Else MsgBox ("User entered " & result) End If End Sub
Would tell the user they canceled when they delete the default string, or they click cancel.
See http://msdn.microsoft.com/en-us/library/6z0ak68w(v=vs.90).aspx
Following example uses InputBox method to validate user entry to unhide sheets: Important thing here is to use wrap InputBox variable inside StrPtr so it could be compared to '0' when user chose to click 'x' icon on the InputBox.
Sub unhidesheet() Dim ws As Worksheet Dim pw As String pw = InputBox("Enter Password to Unhide Sheets:", "Unhide Data Sheets") If StrPtr(pw) = 0 Then Exit Sub ElseIf pw = NullString Then Exit Sub ElseIf pw = 123456 Then For Each ws In ThisWorkbook.Worksheets ws.Visible = xlSheetVisible Next End If End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With