Avatar of Pearlyn Tan
Pearlyn Tan
 asked on

Configure input box on VBA

Hi, I'm trying to create an input box that will exit the sub if the user clicks on "cancel". Here is my current code, but it ends the sub when the user does not key in anything and clicks 'OK'.

Dim strInput As String
strInput = InputBox("Key in Item code")
If strInput = vbNullString Then
 MsgBox ("Cancelled by User")
 Exit Sub
End If

Open in new window


How do I improve it such that clicking "cancel" will exit the sub, yet clicking "ok" when the user had not keyed in anything will prompt a different message ("Please key in Item code")?

Thanks in advance!
VBA

Avatar of undefined
Last Comment
Pearlyn Tan

8/22/2022 - Mon
Rgonzo1971

Hi,

pls try
Dim strInput As String
strInput = Application.InputBox("Key in Item code")
If strInput = "False" Then
 MsgBox ("Cancelled by User")
 Exit Sub
End If

Open in new window

Regards
Ryan Chong

try use function StrPtr:

Dim strInput As String
    strInput = InputBox("Key in Item code")
    If StrPtr(strInput) = 0 Then
        MsgBox ("Cancelled by User")
        Exit Sub
    End If

Open in new window

Rgonzo1971

Corrected code
Dim strInput As String
strInput = Application.InputBox("Key in Item code")
If strInput = "False" Then
    MsgBox ("Cancelled by User")
    Exit Sub
End If
Do
    strInput = Application.InputBox("Please Key in Item code")
    If strInput = "False" Then
        MsgBox ("Cancelled by User")
        Exit Sub
    End If
Loop While strInput = ""

Open in new window

This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
ASKER CERTIFIED SOLUTION
Ryan Chong

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
SOLUTION
Rgonzo1971

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Ryan Chong

ok, but the code will error if user keyed in "False", it makes an expression that it was cancelled by user while user actually entered "False".
Pearlyn Tan

ASKER
Hi Rgonzo1971 and Ryan, thanks so much for both your codes, all worked perfectly. Personally preferred one with a message box prompt if user clicks ok with no input, but nonetheless I appreciate both. Thank you!