0

How to differentiate the action when a user hit CANCEL button or OK button under a Inputbox.

There are two scenarios:
1. To end (Exit Sub) the operation when user hit Cancel/Close button
2. If user hit OK without any value ask him to enter some value.

The code i use satisfy 2nd scenario, is it possible to accommodate 1st scenario as well?

Sub INPUT_BOX()

Re_Enter_Username:
cUsername = INPUTBOX("Username", "Please provide Login Name")
    If cUsername = "" Then
        MsgBox "Please provide a Username"
        GoTo Re_Enter_Username:
    Else 'Code if not empty
    End If

End Sub

I am not sure whether this is possible, may be my exception was more than what VBA can help provide. :) Sorry if so.

And thanks if you have a solution for this.

mithun nair
  • 136
  • 11
  • https://stackoverflow.com/questions/26264814/how-to-detect-if-user-select-cancel-inputbox-vba-excel – braX Nov 13 '17 at 14:35
  • Thanks braX, I went through that stackoverflow question, but that one doesn't satisfy my both the scenarios. – mithun nair Nov 13 '17 at 14:38

1 Answers1

4

You can test using StrPtr like this:

cusername = InputBox("Username", "Please provide Login Name")
    If StrPtr(cusername) = 0 Then
        ' user pressed Cancel
        Exit Sub
    ElseIf cusername = "" Then
        MsgBox "Please provide a Username"
        GoTo Re_Enter_Username:
    Else 'Code if not empty
    End If
Rory
  • 32,730
  • 5
  • 32
  • 35