我在Excel工作表中有一个VBA宏,它刷新SQL查询但受密码保护 - 或者我认为。宏应该如何工作是当您单击按钮时,会出现密码提示,如果输入正确,查询将刷新。如果输入不正确,则不会发生任何事情。
我最近发现,即使有人输错密码,查询也会刷新。如果密码不正确,我会在代码中输入什么来阻止宏运行?
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
答案 0 :(得分:3)
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
如果密码不正确,您应该退出sub。 - ^^
或者您可以创建一个布尔值bCorrect
,以保留密码的结果并退出,如果它是假的.-- v
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