简体   繁体   English

如何使用数组自动过滤条件

[英]How do I autofilter using an array for criteria

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 an excel spreadsheet using those same values. 我想设置一个带有值的数组,然后使用这些相同的值过滤一个Excel电子表格。 I did the below code, but it keeps throwing up an error when I try to autofilter 我做了下面的代码,但是当我尝试自动过滤时,它总是抛出错误

Here is my code 这是我的代码

Dim I As Integer
ReDim arr(1 to var) As Variant 'var is defined in a different function with a #
I = 1
For Each rngValue In rngValues.cells 'rngValues is defined in a different function
    If rngValue ="c" then
       arr(I)=rngValue.Offset(0,2)
    End If
    I = I +1
Next rngValue

arr(I) = "="

With ws1
    .[A1].Autofilter Field:=1, Criteria1:=arr, operator:xlfiltervalues
End With

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

You can pass Range value to array faster by directly passing it like below: 您可以通过如下所示直接传递Range值来更快地将Range值传递给数组:

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. 请注意, rngValue应该只包含一维范围区域。
If however you want to stick with your logic; 但是,如果您想坚持自己的逻辑; also to handle 2-dimension Range or non contiguous ranges, below should work: 也可以处理2维范围或非连续范围,以下应起作用:

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. 在任何情况下,请确保生成的用作过滤器的数组是1D。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM