如何在打开文件时自动删除应用的过滤器而又不删除过滤器功能

时间:2019-05-23 19:30:36

标签: excel vba

我有一个可以远程处理共享电子表格的团队。他们可以将过滤器用于搜索目的。我希望电子表格能够在关闭或打开电子表格时自动清除以前应用的过滤器,而不会删除设置以后的过滤器的功能。我无法弄清楚实现此目的的代码。

我已经搜索了这些线程并尝试了许多代码。有些已经接近并在打开电子表格时删除了过滤器,但是它也删除了进行过滤的能力。这意味着我每次重新打开电子表格时都必须打开过滤,这并不理想。使用的代码是:

Private Sub Workbook_Open()
    Dim ws As Worksheet
        For Each ws In Worksheets
            If ws.AutoFilterMode Then
                ws.AutoFilterMode = False
            End If
        Next ws
End Sub

2 个答案:

答案 0 :(得分:1)

这将清除,但保留过滤器:

Sub Workbook_Open()
    Dim ws As Worksheet
    For Each ws In Worksheets
        If ws.AutoFilterMode Then 
            ws.AutoFilter.ShowAllData
        End If 
    Next ws 
End Sub

答案 1 :(得分:0)

另一种方法可能是:

Sub clearFilter()
Dim sht As Worksheet 'Declare a worksheet variable
Dim rng As Range 'Declare a Range variable
Dim j As Long
Set sht = ThisWorkbook.Worksheets("Name of your Worksheet") 'The worksheet where the data is
Set rng = sht.Range("A:E") 'The range that is being filtered. In this case columns A,B,C,D,E are being filtered.

For j = 1 To rng.Columns.Count Step 1 'loop through all the columns that are being filtered...
    rng.AutoFilter Field:=j '...and clear the filter while maintaining the filtering capabilities
Next j

End Sub