密码input错误的VBAmacros仍然运行

我在Excel工作表中有一个VBAmacros,刷新SQL查询,但密码保护 – 或者我想。 macros如何工作是当你点击button,出现密码提示,如果input正确,查询刷新。 如果input不正确,什么都不应该发生。

我最近发现的是,即使有人不正确地input密码,查询也会刷新。 如果密码不正确,我会input什么代码来停止运行macros?

Sub Button1_Click() Dim password As Variant password = Application.InputBox("Enter Password", "Password Protected") Select Case password Case Is = False 'do nothing Case Is = "Select15" Range("A1").Value = "Code" Case Else MsgBox "Incorrect Password" End Select For Each sh In Worksheets If sh.FilterMode Then sh.ShowAllData Next ActiveWorkbook.RefreshAll End Sub 

 Sub Button1_Click() Dim password As Variant password = Application.InputBox("Enter Password", "Password Protected") Select Case password Case Is = False 'do nothing exit sub Case Is = "Select15" Range("A1").Value = "Code" Case Else MsgBox "Incorrect Password" exit sub End Select For Each sh In Worksheets If sh.FilterMode Then sh.ShowAllData Next ActiveWorkbook.RefreshAll End Sub 

如果密码不正确,您应该退出该子。 – ^^

或者你可以创build一个布尔bCorrect ,保持密码的结果并退出,如果是false的话

 Sub Button1_Click() Dim password As Variant Dim bCorrect As Boolean password = Application.InputBox("Enter Password", "Password Protected") Select Case password Case Is = False 'do nothing Case Is = "Select15" bCorrect = True Range("A1").value = "Code" Case Else MsgBox "Incorrect Password" End Select If Not bCorrect Then Exit Sub For Each sh In Worksheets If sh.FilterMode Then sh.ShowAllData Next ActiveWorkbook.RefreshAll End Sub 

你的用户input的任何值(除了-1)都被编码为“False”,所以你的第一个案例被触发。 检查密码是否正确,作为第一个选项。