Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if user select cancel InputBox VBA Excel

Tags:

excel

vba

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) enter image description here

like image 356
user2103670 Avatar asked Oct 08 '14 19:10

user2103670


People also ask

How does InputBox handle cancellation?

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 do I use InputBox in Excel VBA?

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.

What does InputBox do in VBA?

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.


2 Answers

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

like image 163
djv Avatar answered Sep 28 '22 05:09

djv


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 
like image 36
Kash Avatar answered Sep 28 '22 05:09

Kash