如何检查InputBox exit(X)vs空字符串

时间:2016-08-18 11:12:53

标签: excel vba excel-vba

我有一个命令按钮,可以启动输入框以输入密码。

Private Sub CommandButton1_Click()  
     Dim ThePW As String

     ThePW = InputBox("A password is required to run this procedure." & vbCrLf & _
        "Please enter the password:", "Password")

     If ThePW <> "123" Then MsgBox ("wrong pw")
End Sub

但是,当我点击退出(X)或取消时,消息框仍会显示wrong pw

我该如何解决这个问题?当我点击退出(X)或选择取消时,我不希望它显示wrong pw

1 个答案:

答案 0 :(得分:0)

使用下面的代码,如果他点击取消,它就会退出Sub

Private Sub CommandButton1_Click()

Dim ThePW As String

ThePW = InputBox("A password is required to run this procedure." & vbCrLf & _
"Please enter the password:", "Password")

If ThePW = "" Then Exit Sub ' Exit if null input or cancel

If ThePW <> "123" Then
    MsgBox ("wrong pw")
Else
    ' do something if OK
End If        

End Sub