VBAinput框将不会closures

我目前有一个如下所示的代码,用于input密码以启动代码。 我是一个VBA noob所以请容易对我。

问题:当出现input框提示符时,如果密码正确,则工作正常。 如果这是不正确的,你有更多的机会再次进入,但让我们说你不知道密码,并想closures窗口,你不能。 “x”选项和取消选项只会导致input框提示刷新而不是closures窗口。 我如何设置窗口closures?

这里是书面forms的代码:

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 

添加一个检查,看看它是否是一个空string,如下所示:

  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 

如果您需要将空string视为有效的input值,则检查InputBox实际取消的唯一方法不是将其结果与vbNullString"" (都为True )进行比较。

因此,您可以使用(未​​logging的) StrPtr函数来确定InputBox调用是否返回了合法的空string,或者是否用[X]或[Cancel]button主动取消了该string:

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

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

@braXbuild议是一个很好的解决scheme。 另外,在这种情况下,您可以将尝试次数限制为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