Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA Input Box will not close

Tags:

excel

vba

I currently have a code shown below for entering a password to have the code start. I am a VBA noob so please go easy on me.

Issue: When the input box prompt appears it works fine if the password is correct. If it is incorrect you are given more opportunities to enter it again but lets say you do not know the password and want to close the window, you cannot. The "x" option and cancel options will just cause the input box prompt to refresh rather than closing the window. How can I set the window up to close?

Here is the code in written form:

    Sub Pword()

        Dim Ans As Boolean
        Const Pword As String = "black2"

        Ans = False

        Do While Ans = False
            If InputBox("Please enter password to continue.", "Enter Password") = Pword Then
                Ans = True
            End If
        Loop

Sheets("Workshop").Range("B15:B20") = ""
Sheets("Workshop").Range("B24:B29") = ""
Sheets("Workshop").Range("B33:B35") = ""
Sheets("Workshop").Range("E5:E11") = ""
Sheets("Workshop").Range("E15:E26") = ""
Sheets("Workshop").Range("H5:H17") = ""

MsgBox "All data has been cleared."


End Sub
like image 965
jallington Avatar asked Dec 12 '25 06:12

jallington


2 Answers

If you need to consider an empty string as a valid input value, the only way to check if the InputBox was actually cancelled isn't to compare its result with vbNullString or "" (both will be True).

So you can use the (undocumented) StrPtr function to determine if the InputBox call returned a legit empty string, or if it was actively cancelled with the [X] or [Cancel] button:

Dim result As String
result = InputBox(...)
If StrPtr(result) = 0 Then
    ' inputbox was cancelled
    Exit Sub
Else
    ' todo: validate result
End If

Combine that with the other answers to get a reliable "retry" mechanism.

like image 91
Mathieu Guindon Avatar answered Dec 14 '25 20:12

Mathieu Guindon


Add a check to see if it's an empty string, like this:

    Dim sResult As String
    Do While Ans = False
        sResult = InputBox("Please enter password to continue.", "Enter Password")
        If sResult = Pword Then
            Ans = True
        ElseIf sResult = "" Then
            Exit Do ' or Exit Sub depending on what you want to happen afterwards
        End If
    Loop
like image 28
braX Avatar answered Dec 14 '25 20:12

braX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!