excel - 在 Excel VBA 中,如何保存/恢复用户定义的过滤器?

标签 excel vba filter

如何使用 VBA 保存并重新应用当前过滤器?

在 Excel 2007 VBA 中,我正在尝试

  1. 保存用户在当前工作表上拥有的任何过滤器
  2. 清除过滤器
  3. “做事”
  4. 重新应用已保存的过滤器

最佳答案

看看Capture Autofilter state

为了防止链接失效,这里是代码(感谢原作者):

适用于Excel 2010,只需删除标记的注释行即可。

Sub ReDoAutoFilter()
    Dim w As Worksheet
    Dim filterArray()
    Dim currentFiltRange As String
    Dim col As Integer

    Set w = ActiveSheet

    ' Capture AutoFilter settings
    With w.AutoFilter
        currentFiltRange = .Range.Address
        With .Filters
            ReDim filterArray(1 To .Count, 1 To 3)
            For f = 1 To .Count
                With .Item(f)
                    If .On Then
                        filterArray(f, 1) = .Criteria1
                        If .Operator Then
                            filterArray(f, 2) = .Operator
                            filterArray(f, 3) = .Criteria2 'simply delete this line to make it work in Excel 2010
                        End If
                    End If
                End With
            Next f
        End With
    End With

    'Remove AutoFilter
    w.AutoFilterMode = False

    ' Your code here

    ' Restore Filter settings
    For col = 1 To UBound(filterArray(), 1)
        If Not IsEmpty(filterArray(col, 1)) Then
            If filterArray(col, 2) Then
                w.Range(currentFiltRange).AutoFilter field:=col, _
                Criteria1:=filterArray(col, 1), _
                Operator:=filterArray(col, 2), _
                Criteria2:=filterArray(col, 3)
            Else
                w.Range(currentFiltRange).AutoFilter field:=col, _
                Criteria1:=filterArray(col, 1)
            End If
        End If
    Next col
End Sub

关于excel - 在 Excel VBA 中,如何保存/恢复用户定义的过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9489126/

相关文章:

Excel 2010 - 单元格和形状着色 - 我的想法

search - 过滤一个新的自定义字段 Phreeze

image-processing - 推导图像卷积核的逆滤波器

excel - VBA Excel将数据打印到有关范围数据的即时窗口中以测试理解

django ModelMultipleChoiceField 查询集/过滤器已关联的对象

json - 手动使用 Jira Rest API 与以编程方式使用 Jira Rest API 有区别吗?

excel - excel中PI()和3.14159265358979的计算

excel - 如何在Excel生成Jasper报告中添加VBA Excel脚本?

excel - 如何将列从 MS Excel 添加到 MS Project - VBA

excel - 如何在插入函数对话框中隐藏 protected Excel 加载项函数?