3

我正在使用以下代码来尝试检测应用于表中列的过滤器,然后清除过滤器:

If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData

根据微软文档:

如果工作表包含一个过滤列表,其中有隐藏的行,则此属性为真。

情况似乎并非如此,因为只有在选择了应用过滤器的表格内的单元格时ActiveSheet.Filtermode才会返回。True

  • 第一个问题:文档有错吗?文档

  • 第二个问题:我唯一的选择是在表格中选择一个单元格以使表达式返回 True 吗?

PS我正在使用Excel 2010

编辑:回答问题 2,基于非选择的方法来清除过滤器......

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

4

2 回答 2

2

False我可以在 Excel 2013上复制您的两个问题:错误FilterMode和错误ShowAllData

作为对文档是否错误的回应,我会说缺少资格说 theActiveCell应该在ListObjectsDataBodyRange中。也许文档是正确的,但这是一个尚未解决的错误。也许您可以通过文档链接更新您的问题?

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

这就是我使用该Intersect功能检查它ActiveCell当前是否在以下区域中的DataBodyRange方法ListObject

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 的评论:

如果您跳过 If Intersect(rng, lst.DataBodyRange) Is Nothing Then 并使用 If lst.AutoFilter.FilterMode Then lst.AutoFilter.ShowAllData End If 会发生什么?

所以,你可以检查FilterModeListObject本身,然后只要你有引用ListObject你就可以使用他的代码:

If lst.AutoFilter.FilterMode Then 
    lst.AutoFilter.ShowAllData 
End If
于 2016-08-28T11:53:33.127 回答
2

一个更简单的选择可以是AutoFit所有行:

Rows.AutoFit

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


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
于 2016-08-28T16:08:31.930 回答