VBA: Autofilter for Partial Array strings

前端 未结 1 1836
忘掉有多难
忘掉有多难 2020-12-21 19:48

I need to filter a column for the array I\'ve made. I\'m trying to use Cells.AutoFilter Field:=14, Criteria1:=stringArray, Operator:= but I don\'t know what the

相关标签:
1条回答
  • 2020-12-21 20:20

    You cannot use wildcards in more than two criteria of the AutoFilter Method and then it must be like either,

    .AutoFilter Field:=1, Criteria1:="=abc*", Operator:=xlAnd, Criteria2:="=def*"
    ' or,
    .AutoFilter Field:=1, Criteria1:="=abc*", Operator:=xlOr, Criteria2:="=def*"
    

    After splitting the string into a variant array, simply loop through the elements of the array and append an asterisk (e.g. Chr(42)) to each element.

    Sub Macro3()
        Dim v As Long, vFilters As Variant, sFilters As String
        Dim xCell As Range
    
        With Sheets("Sheet1")
            Set xCell = .Range("ZZ99")
            sFilters = xCell.Offset(0, 2) 'this cell may have multiple entries such as "a, b, c"
            vFilters = Split(sFilters, ", ")
            With .Cells(1, 1).CurrentRegion
                For v = LBound(vFilters) To LBound(vFilters)
                    .Cells.AutoFilter Field:=14, Criteria:=vFilters(v) & Chr(42) 'begins with filter
                    'move down a row to save the header and resize -1 row
                    With .Resize(.Rows.Count - 1, .Columns.Count).offswet(1, 0)
                        'check if there is anything visible
                        If CBool(Application.Subtotal(103, .Columns(14))) Then
                            'do something with
                            '.Cells.SpecialCells (xlCellTypeVisible)
                        End If
                    End With
                Next v
            End With
        End With
    
    End Sub
    

    If you need more than two 'wildcarded' criteria at once, a significantly larger amount of coding can be used to build an array to pass into the filter and then use the Operator:=xlFilterValues option.

    0 讨论(0)
提交回复
热议问题