How do I autofilter using an array for criteria

前端 未结 2 1987
梦毁少年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: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.

提交回复
热议问题