我有一张纸(“设置”),大部分时间都需要隐藏。我创建了一个设置用户窗体,其中包含各种设置按钮和切换按钮,其中隐藏/显示该隐藏工作表(然后单击并输入密码)。
隐藏/显示工作表的宏:
Private Sub SettingsTB_Click()
Dim strPassTry As String
Dim strPassword As String
Dim lTries As Long
Dim bSuccess As Boolean
If SettingsTB.Value = True Then
strPassword = "asd"
For lTries = 1 To 3
strPassTry = InputBox("Enter password", "Show Settings sheet")
If strPassTry = vbNullString Then Exit Sub
bSuccess = strPassword = strPassTry
If bSuccess = True Then Exit For
MsgBox "Incorrect password"
Next lTries
If bSuccess = True Then
Worksheets("Settings").Visible = True
End If
Else
Worksheets("Settings").Visible = xlSheetHidden
End If
End Sub
该宏按预期工作,出现问题,然后打开UserForm,“设置”工作表仍然可见。 UserForm_Initialize事件触发SettingsTB_Click事件(要求输入密码)。
UserForm_initialize中的代码用于记住切换按钮的位置(没有该代码,每次打开UserForm时,都处于FALSE位置)
Private Sub UserForm_Initialize()
If Worksheets("Settings").Visible = True Then
SettingsTB.Value = True
Else
SettingsTB.Value = False
End If
End Sub
是否可以阻止SettingsTB_Click在UserForm_Initialize上触发,还是应该使用完全不同的方法?
答案 0 :(得分:1)
使用公共变量或标记属性停止点击事件的运行。
Private Sub SettingsTB_Click()
Dim strPassTry As String
Dim strPassword As String
Dim lTries As Long
Dim bSuccess As Boolean
If SettingsTB.Tag Then Exit Sub
If SettingsTB.Value = True Then
strPassword = "asd"
For lTries = 1 To 3
strPassTry = InputBox("Enter password", "Show Settings sheet")
If strPassTry = vbNullString Then Exit Sub
bSuccess = strPassword = strPassTry
If bSuccess = True Then Exit For
MsgBox "Incorrect password"
Next lTries
If bSuccess = True Then
Worksheets("Settings").Visible = True
End If
Else
Worksheets("Settings").Visible = xlSheetHidden
End If
End Sub
Private Sub UserForm_Initialize()
SettingsTB.Tag = True
If Worksheets("Settings").Visible = True Then
SettingsTB.Value = True
Else
SettingsTB.Value = False
End If
SettingsTB.Tag = False
End Sub