显示工作簿上的所有自动筛选数据关闭保存密码保护

时间:2017-05-18 12:18:28

标签: excel excel-vba vba

当工作表关闭时,我有以下代码显示所有过滤数据,但是如何在受保护的工作表上执行此操作,因为有些用户习惯删除重要元素片

Option Explicit
Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Dim sh As Variant
    For Each sh In Worksheets
         If sh.FilterMode Then sh.ShowAllData
    Next
End Sub
Private Sub Workbook_Open()
    Dim sh As Variant
    For Each sh In Worksheets
      If sh.FilterMode Then sh.ShowAllData
    Next
End Sub

1 个答案:

答案 0 :(得分:0)

因此,如果您取消保护表格,运行您的宏,然后再次保护,这将解决您的For loop你的问题。

出于这个原因,我将在您的代码中添加Worksheet.Unprotect.Protect

Option Explicit
Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Dim sh As Variant
    For Each sh In Worksheets
         sh.Unprotect Password:= "YourPasswordHere"     'leave this quotation marks empty if you don't have password
         If sh.FilterMode Then sh.ShowAllData
        sh.Protect Password:= "YourPasswordHere"
    Next
End Sub
Private Sub Workbook_Open()
    Dim sh As Variant
    For Each sh In Worksheets
      sh.Unprotect Password:= "YourPasswordHere"  
      If sh.FilterMode Then sh.ShowAllData
      sh.Protect Password:= "YourPasswordHere"
    Next
End Sub

PS:作为一个选项,您还可以使用以下代码控制用户可以在受保护工作表中使用哪些功能,您可以更改 False / True 来执行操作。

.Protect DrawingObjects:=False, Contents:=True, Scenarios:= _
False, AllowFormattingCells:=True, AllowFormattingColumns:=True, _
AllowFormattingRows:=True, AllowInsertingColumns:=True, AllowInsertingRows _
:=True, AllowInsertingHyperlinks:=True, AllowDeletingColumns:=True, _
AllowDeletingRows:=True, AllowSorting:=True, AllowFiltering:=True, _
AllowUsingPivotTables:=True, UserInterfaceOnly:=True
.EnableOutlining = True