如何过滤和排序 excel table(listobject) in protected sheet

How to filter and sort excel table(listobject) in protected sheet

可以在有或没有 VBA 的情况下对受保护的 Excel sheet 中的 table(列表对象)进行过滤和排序?

此VBA代码允许过滤但不允许排序

ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True _
    , AllowSorting:=True, AllowFiltering:=True

此VBA代码不过滤和排序!!!

ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True _
    , AllowSorting:=True, AllowFiltering:=True
ActiveSheet.Protect Password:="tt"

我找到了解决问题的方法,所以分享给你。

想法是有一个按钮来取消保护 sheet 并允许过滤和排序。 当 sheet 未受保护并且您单击与 table header 不同的地方时,sheet 再次受到保护。

将此代码放入工作sheet模块

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim ol As ListObject

    Set ol = ActiveSheet.ListObjects(1)

    ' This sets the Target to only one cell range when sort is used
    Dim cnt As Integer: cnt = Target.CountLarge
    If cnt > 1 Then Set Target = Range(Split(Target.Address, ":")(0))

    ' It protects the sheet if different cell from table header is selected
    If Intersect(Target, ol.HeaderRowRange) Is Nothing And editMode Then
        Call wsProtect
    End If

    Set ol = Nothing
End Sub

将此代码放入标准模块

Option Explicit

Public editMode As Boolean

Sub wsProtect()
    editMode = False

    ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True _
        , AllowSorting:=True, AllowFiltering:=True
    ActiveSheet.Protect Password:="tt", UserInterfaceOnly:=True
End Sub

Sub wsUnProtect()
    editMode = True

    ActiveSheet.Unprotect Password:="tt"
End Sub

Sub enableEditMode()
    wsUnProtect
End Sub