首页 > 解决方案 > 如何在受保护的工作表中过滤和排序excel表(listobject)

问题描述

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

此 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"

标签: excellistobject

解决方案


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

这个想法是有一个按钮来取消保护工作表并允许过滤和排序。当工作表不受保护并且您单击与表头不同的位置时,工作表将再次受到保护。

将此代码放在工作表模块中

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

推荐阅读