Search code examples
excellistobject

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


It's possible to filter and sort a table (listobject) in protected Excel sheet with or without VBA?

This VBA code allows to filter but does not allow to sort

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

This VBA code does not to filter and sort !!!

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

Solution

  • I found a way to solve my problems, so I share it to you.

    The idea is to have a button to unprotect the sheet and allow filtering and sorting. When the sheet is unprotected and you click somewhere different from the table header, the sheet is protected again.

    Put this code in the worksheet module

    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
    

    Put this code in a standard module

    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