为什么 ActiveSheet.FilterMode returns False 当 sheet 有过滤器?

Why does ActiveSheet.FilterMode returns False when sheet has filter?

我正在使用以下代码尝试检测应用于 table 中列的筛选器,然后清除筛选器:

If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData

根据 Microsoft 文档:

This property is true if the worksheet contains a filtered list in which there are hidden rows.

这似乎不是这种情况,因为 ActiveSheet.Filtermode 只有 returns True 如果 table 中应用过滤器的单元格是 selected.

PS 我正在使用 Excel 2010

编辑:问题 2 的答案,非select 清除过滤器的方法...

If ActiveSheet.ListObjects(1).Autofilter.FilterMode Then ActiveSheet.ListObjects(1).Autofilter.Showalldata

我可以在 Excel 2013 上复制您的两个问题:FilterMode 上的错误 FalseShowAllData.

上的错误

针对文档是否错误,我会说缺少一个资格说ActiveCell应该在ListObjects DataBodyRange。也许文档是正确的,但这是一个尚未解决的错误。也许您可以使用 link 更新您的问题到文档?

关于您的第二个问题 - 我同意使用此解决方法是最明显的解决方案。使用 Select 似乎有点不愉快,但有时我想这是无法避免的。

这就是我使用 Intersect 函数来检查 ActiveCell 当前位于 ListObjectDataBodyRange 区域的方法:

Option Explicit

Sub Test()

    Dim rng As Range
    Dim ws As Worksheet
    Dim lst As ListObject

    'get ActiveCell reference
    Set rng = ActiveCell

    'get reference to Worksheet based on ActiveCell
    Set ws = rng.Parent

    'is there a Listobject on the ActiveCells sheet?
    If ws.ListObjects.Count > 0 Then
        Set lst = ws.ListObjects(1)
    Else
        Debug.Print "No table found"
        Exit Sub
    End If

    'is cell is in the DataBodyRange of ListObject?
    If Intersect(rng, lst.DataBodyRange) Is Nothing Then
        'set the ActiveCell to be in the DataBodyRange
        lst.DataBodyRange.Cells(1, 1).Select
    End If

    'now you can safely call ShowAllData
    If ws.FilterMode = True Then
        ws.ShowAllData
    End If

End Sub

编辑

进一步@orson 的评论:

What happens if you skip the If Intersect(rng, lst.DataBodyRange) Is Nothing Then and use If lst.AutoFilter.FilterMode Then lst.AutoFilter.ShowAllData End If ?

因此,您可以检查 ListObject 本身的 FilterMode 然后只要您有对 ListObject 的引用就可以使用他的代码:

If lst.AutoFilter.FilterMode Then 
    lst.AutoFilter.ShowAllData 
End If

一个更简单的替代方法是 AutoFit 所有行:

Rows.AutoFit

问题在于它将取消隐藏并自动适应活动 sheet 上的所有行。


更新自http://www.contextures.com/excelautofilterlist.html

Dim list As ListObject

For Each list ActiveSheet.ListObjects
    If list.AutoFilter.FilterMode Then
        list.AutoFilter.ShowAllData
    End If
Next