VBA - 使用部分标头匹配应用过滤器

时间:2018-03-28 14:01:54

标签: vba excel-vba ms-office excel

我发布了一个宏观解决方案的问题,即根据标题匹配在多个工作表中应用过滤器。

链接:Loop Through Multiple Worksheets and Apply Filter

我需要部分标题匹配的帮助,而不仅仅是完全匹配,因为,某些标题不会与标准完全匹配 - 也就是说,某些标题会将“STATUS”作为标题,有些将是“ 前缀 _Status“,其他”CurrentStatus“等等。所以我需要使用Instr函数(除非有更好的选择)才能找到包含单词的任何标题状态但我似乎无法弄清楚在哪里或如何使用它..

我有当前的解决方案,会在Match行引发以下错误:

  

类型不匹配

Sub WorksheetLoop()

         Dim WS_Count As Integer
         Dim I As Integer

         ' Set WS_Count equal to the number of worksheets in the active
         ' workbook.
         WS_Count = ActiveWorkbook.Worksheets.count

         ' Begin the loop.
         For I = 1 To WS_Count

            Dim count As Integer, rngData As Range

            With Worksheets(I)
                Set rngData = .Range("A1").CurrentRegion

                count = Application.Match("*STATUS*", Worksheets(I).Range("A1:AZ1"), 0)

                If Not IsError(count) Then
                    rngData.autofilter Field:=count, Criteria1:="INACTIVE"
                End If

            End With

         Next I

End Sub

1 个答案:

答案 0 :(得分:1)

找不到匹配项时,

Application.Match会返回错误。您使用IsError检查错误,但代码在此之前停止。您需要跳过错误,以便稍后可以在代码中捕获它们。

尝试添加:On Error Resume Next

完整代码:

Sub WorksheetLoop()
    Dim WS_Count As Integer, i As Integer, count As Integer
    Dim rngData As Range

    ' Set WS_Count equal to the number of worksheets in the active
    ' workbook.
    WS_Count = ActiveWorkbook.Worksheets.count

    'If Application.Match finds no match it will throw an error so we need to skip them
    On Error Resume Next

    ' Begin the loop.
    For i = 1 To WS_Count
       With Worksheets(i)
           count = Application.Match("*STATUS*", Worksheets(i).Range("A1:AZ1"), 0)

           If Not IsError(count) Then
               Set rngData = .Range("A1").CurrentRegion
               rngData.AutoFilter Field:=count, Criteria1:="INACTIVE"
           End If
       End With
    Next i
End Sub

在简单数据集上测试

在:

enter image description here

后:

enter image description here