How do I autofilter using an array for criteria

前端 未结 2 1990
梦毁少年i
梦毁少年i 2021-01-28 04:47

I am just learning about using arrays and am a bit stuck on how to use arrays as an input for criteria in autofiltering. I would like to set an array with values and then filter

相关标签:
2条回答
  • 2021-01-28 05:08

    May be you could try this

       fil = Split(Join(Application.Transpose(Range("list")))) ' here list is the name of the range
        Range("A1").AutoFilter field:=1, Criteria1:=fil, Operator:=xlFilterValues 'it will only filter the list values
    
    0 讨论(0)
  • 2021-01-28 05:10

    You can pass Range value to array faster by directly passing it like below:

    Dim arr As Variant '~~> no need to re-dimension
    arr = Application.Transpose(rngValues) '~~> Transpose produces 1D array
    ws1.Range("A1").AutoFilter 1, arr, xlFilterValues
    

    Note that rngValue should contain one dimension Range area only.
    If however you want to stick with your logic; also to handle 2-dimension Range or non contiguous ranges, below should work:

    Dim i As Long: i = 1
    ReDim arr(1 to rngValues.Cells.Count)
    For Each rngValue In rngValues
        arr(i) = rngValue.Value
        i = i + 1
    Next
    ws1.Range("A1").AutoFilter 1, arr, xlFilterValues
    

    In any of the scenarios, make sure that the array produced to be used as filter is 1D.

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