关闭时设置密码

Set password when closing

我试图在关闭工作簿时使用密码锁定所有工作表,但允许过滤和搜索表格。

我设法收集了以下除了设置密码外还有效的信息。

Private Sub Workbook_BeforeClose(Cancel As Boolean)
'Update by Extendoffice 2018/1/24
Dim xSheet As Worksheet
Dim xPsw As String
xPsw = "***"
For Each xSheet In Worksheets
    xSheet.Protect xPsw
Next
If ActiveSheet.Protection.AllowFiltering = False Then
    ActiveSheet.Protect AllowFiltering:=True
End If
End Sub

*** = 密码
以上自动锁定工作表并允许根据需要进行过滤但不设置密码。

Excel 适用于 Office 365、win10 企业版。

我认为它有问题,因为你使用了两次保护方法。试试下面的代码

Private Sub Workbook_BeforeClose(Cancel As Boolean)
'Update by Extendoffice 2018/1/24
Dim wb As Workbook: Set wb = ThisWorkbook
Dim xSheet As Worksheet
Dim xPsw As String
xPsw = "testpw"
For Each xSheet In wb.Worksheets
   xSheet.Protect xPsw, AllowFiltering:=True
Next
End Sub