使用数组和 xlFilterValues 过滤 [英] Filter using array and xlFilterValues

查看:59
本文介绍了使用数组和 xlFilterValues 过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个代码,它定义了一个数组,然后使用该数组作为过滤范围的条件.这是代码的摘录.它以某种方式过滤掉所有内容,不显示过滤后的值.

I have written a code which defines an array and then uses that array as criteria to filter a range. Here's the extract of the code. Somehow it filters out everything and does not display the filtered values.

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

推荐答案

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

Are the values in column A numbers? When using a variant array as the Criteria1 with xlFilterValues, numbers must be treated as text so use ary(i) = CStr(.Cells(i, 1).Value2) to build your array.

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 的数组过滤数字的方法.日期可能会出现类似的问题.

Yes, this seems counter-intuative but that is how to filter for numbers using an array with xlFilterValues. Dates can present a similar issue.

这篇关于使用数组和 xlFilterValues 过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆