可以将AutoFilter捕获为事件吗?

时间:2016-09-01 00:08:08

标签: excel vba excel-vba

我正在尝试向报表中的用户显示过滤列。 Excel提供了一个不同的图标,但对于大号没有。列可以很好地为另一种颜色的列着色,如蓝色。

我在Is there a way to see which filters are active in Excel, other than just the funnel icons?

找到了代码
  • 它适用于我,但如何在没有任何按钮的情况下启动此代码
  • SheetChange和选择更改不起作用。

Sub test()
Call markFilter(ActiveSheet)
End Sub


Sub markFilter(wks As Worksheet)

    Dim lFilCol As Long

    With wks
        If .AutoFilterMode Then
            For lFilCol = 1 To .AutoFilter.Filters.Count

                '/ If filter is applied then mark the header as bold and font color as red
                If .AutoFilter.Filters(lFilCol).On Then
                    .AutoFilter.Range.Columns(lFilCol).Cells(1, 1).Font.Color = vbRed
                    .AutoFilter.Range.Columns(lFilCol).Cells(1, 1).Font.Bold = True
                Else
                     '/ No Filter. Column header font normal and black.
                    .AutoFilter.Range.Columns(lFilCol).Cells(1, 1).Font.Color = vbBlack
                    .AutoFilter.Range.Columns(lFilCol).Cells(1, 1).Font.Bold = False
                End If
            Next
        Else
            '/ No Filter at all. Column header font normal and black.
            .UsedRange.Rows(1).Font.Color = vbBlack
            .UsedRange.Rows(1).Font.Bold = False
        End If
    End With
End Sub

2 个答案:

答案 0 :(得分:4)

我将使用您在帖子中提到的答案中使用的相同示例。我回答了。 :)

excel中没有过滤器更改事件。我将使用的一种解决方法是捕获工作表的计算方法或更好的工作簿。

因此,在带有过滤器的工作表中添加如下虚拟公式:=SUBTOTAL(3,Sheet2!$A$1:$A$100)这仅计算可见单元格。但它取决于你。随意使用任何响应过滤器更改的公式。

here

之后,转到工作簿的代码并添加:

Private Sub Workbook_SheetCalculate(ByVal Sh As Object)
     Call markFilter(Sh)
     MsgBox "Filter changed"  
End Sub

动臂。现在,您正在捕获过滤器更改事件,它将通过触发vba代码来更新已过滤的列。

注意markFilter来自您提到的enter image description here

答案 1 :(得分:0)

我的文章Trapping a change to a filtered list with VBA

的要点
  1. A" dummy" WorkSheet在SUBTOTAL中添加了一个A1公式,指向主表上正在过滤的范围。
  2. Worksheet_Calculate()事件添加到"虚拟" WorkSheet,当更改过滤器时SUBTOTAL公式更新时,将触发此事件。
  3. 只有在需要将工作簿计算作为Manual

    运行时,才需要接下来的两个步骤
    1. 添加Workbook_Open事件以设置除" Dummy"以外的所有工作表的EnableCalculation属性为假。
    2. 计算模式
    3. 运行工作簿