使用array和xlFilterValues进行过滤

时间:2017-03-21 16:03:57

标签: arrays excel vba excel-vba autofilter

我编写了一个定义数组的代码,然后使用该数组作为条件来过滤范围。这是代码的摘录。不知何故,它会过滤掉所有内容并且不会显示过滤后的值。

Dim N As Long

Sheets("Calculations").Select

With Sheets("Calculations")
        N = .Cells(Rows.Count, "A").End(xlUp).Row
        ReDim ary(1 To N)
        For i = 1 To N
            ary(i) = .Cells(i, 1)
        Next i
End With

    Sheets("Data").Select
    Range(Range("A1"), Range("A1").End(xlToRight)).Select
    Range(Selection, Selection.End(xlDown)).Select

    With Selection
        .AutoFilter Field:=36, Criteria1:=ary, Operator:=xlFilterValues
    End With

2 个答案:

答案 0 :(得分:2)

A列中的值是否为数字?当使用变量数组作为带有xlFilterValues的Criteria1时,必须将数字视为文本,因此使用ary(i) = CStr(.Cells(i, 1).Value2)来构建数组。

Dim ary As Variant

With Worksheets("sheet1").Cells(1, 1).CurrentRegion
    'with true numbers in column A this DOES NOT work
    ary = Array(1, 2, 3)
    .AutoFilter field:=1, Criteria1:=ary, Operator:=xlFilterValues
     'with true numbers in column A this DOES work
    ary = Array("1", "2", "3")
    .AutoFilter field:=1, Criteria1:=ary, Operator:=xlFilterValues
End With

是的,这似乎是反直觉的,但这就是如何使用带有xlFilterValues的数组过滤数字。日期可能会出现类似的问题。

答案 1 :(得分:0)

按数组过滤时,必须使用转置方法:

Criteria1:=后,您的代码应为Application.Transpose(ary)