【问题标题】:Unprotect sheet prompt for PW only when AllowFiltering = True仅当 AllowFiltering = True 时为 PW 取消保护工作表提示
【发布时间】:2023-03-06 19:53:01
【问题描述】:

我有两个非常简单的子程序来保护和取消保护带有密码的工作表。在我添加“AllowFiltering:=True”参数之前,Subs 工作得很好。

添加该参数后,取消保护工作表时会提示我输入密码。但是,如果我按取消,则工作表不受保护(应该如此)。

因此,密码提示似乎完全多余,但有人可以帮我摆脱它吗?

这两个子是:

Sub LockSheet()

If ActiveSheet.Protect = False Then
ActiveSheet.Protect Password:="TopSecretPW", DrawingObjects:=True, Contents:=True, Scenarios:=True, AllowFiltering:=True
End If

End Sub


Sub UnlockSheet()

If ActiveSheet.Unprotect = False Then
ActiveSheet.Unprotect Password:="TopSecretPW"
End If

End Sub

如果我使用此宏 - 没有 AllowFiltering:=True 参数 - 系统不会提示我输入密码。

Sub LockSheet()

If ActiveSheet.Protect = False Then
ActiveSheet.Protect Password:="TopSecretPW", DrawingObjects:=True, Contents:=True, Scenarios:=True
End If

End Sub

奖励信息:过滤器和保护在参数集下工作得很好,如果没有输入正确的密码,我无法从菜单中取消保护工作表。我想埋葬的只是那个不请自来的私信提示。

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    问题在于您如何检查工作表是否受到保护。 ActiveSheet.Protect 是一种方法,而不是工作表对象的属性。而不是使用If ActiveSheet.Protect 使用If ActiveSheet.ProtectContents。 ProtectContents 是 WorkSheet 对象的一个​​属性,如果工作表受保护则返回 true,否则返回 false。您修改后的代码应如下所示:

    Sub LockSheet()
    
    If ActiveSheet.ProtectContents = False Then
        ActiveSheet.Protect Password:="TopSecretPW", DrawingObjects:=True, Contents:=True, Scenarios:=True, AllowFiltering:=True
    End If
    
    End Sub
    
    
    Sub UnlockSheet()
    
    If ActiveSheet.ProtectContents = True Then
        ActiveSheet.Unprotect Password:="TopSecretPW"
    End If
    
    End Sub
    

    【讨论】:

    • 你太棒了 - 它可以工作!...虽然,我不确定我是否理解如何解释没有过滤器参数集的代码可以正常工作,并且我无法解锁没有 PW 的菜单中的工作表,但我可以取消 PW 提示并取消保护工作表,当运行 unprotect sub 时......暂时不要介意。它有效,这很重要......再次感谢。
    • 没问题。有趣的是 VBA 如何处理您的代码......基本上“If”语句本身正在尝试保护或取消保护您的工作表的方法。不是 100% 确定原因,但不知何故,在 Excel 中,如果不包含“AllowFiltering”属性,它认为不需要密码来取消保护工作表。实际上,您的 If 语句说“如果 ActiveSheet.Unprotect 不起作用(等于 false)则......”并且由于该命令在没有提供密码的情况下工作,因此从未触发过“If”的内部。跨度>
    猜你喜欢
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多