VBA输入框不会关闭

时间:2017-11-13 19:40:50

标签: excel vba excel-vba

我目前有一个如下所示的代码,用于输入密码以启动代码。我是VBA的菜鸟,所以请放轻松我。

问题:当出现输入框提示时,如果密码正确,则可以正常工作。如果它不正确,你会有更多的机会再次输入它,但是假设你不知道密码而想要关闭窗口,你就不能。 “x”选项和取消选项只会导致输入框提示刷新而不是关闭窗口。如何设置窗口关闭?

以下是书面形式的代码:

    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

3 个答案:

答案 0 :(得分:4)

如果您需要将空字符串视为有效输入值,检查InputBox 实际取消的唯一方法是不将其结果与{{1 }或vbNullString(两者都是"")。

因此,您可以使用(未​​记录的)True函数来确定StrPtr调用是否返回了合法的空字符串,或者是否使用[X]或[取消]主动取消 ]按钮

InputBox

将其与其他答案相结合,以获得可靠的“重试”机制。

答案 1 :(得分:2)

添加一项检查以查看它是否为空字符串,如下所示:

    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

答案 2 :(得分:2)

@braX建议是一个很好的解决方案。 此外,您可以将尝试限制为n,在这种情况下,我将尝试限制为3

 Dim sResult As String
 Dim Attmp As Integer
 Attmp = 0
    Do While Ans = False
        sResult = InputBox("Please enter password to continue.", "Enter Password")
        If sResult = Pword Then
            Ans = True
        ElseIf sResult = "" Then
            Attmp = Attmp + 1
            If Attmp = 3 Then 
                Msgbox "Maximum attempts reached."
                Exit Do
            End If
        End If
    Loop
相关问题