简体   繁体   English

使用可变Excel范围在自动筛选VBA中使用

[英]Use a variable Excel range to use in autofilter VBA

I've searched a lot and tried a lot of different things, but I can't get the following to work. 我进行了很多搜索,并尝试了很多不同的方法,但无法满足以下要求。

I have a range of IDs that I generate. 我生成了一系列ID。 I then want to filter a range of data to produce a filtered output of just the specified IDs. 然后,我想过滤一系列数据以生成仅具有指定ID的过滤输出。 However, whatever I try, my filtered output just returns a blank range. 但是,无论我如何尝试,经过过滤的输出都只会返回一个空白范围。

Please note: my range of IDs varies in size each time I run this process. 请注意:每次运行此过程时,我的ID范围会有所不同。 I've included a very simplistic set of data to illustrate my point - my real data is far more complex than my example. 我提供了一组非常简单的数据来说明我的观点-我的实际数据比我的示例要复杂得多。

The code I have at the moment: 我目前拥有的代码:

Sub Test()

    Dim Template As Workbook
    Set Template = ThisWorkbook
    Dim IDs, Report As Worksheet
    Set IDs = Template.Worksheets("IDs")
    Set Report = Template.Worksheets("Report")

    Dim LastRowIDs As Long
    LastRowIDs = IDs.Range("A" & IDs.Rows.Count).End(xlUp).Row

    Dim IDsArray As Variant

    IDsArray = IDs.Range("A2:A" & LastRowIDs)

    Dim LastRowReport As Long
    LastRowReport = Report.Range("A" & Report.Rows.Count).End(xlUp).Row

    Report.AutoFilterMode = False
    Report.Range("A1:C" & LastRowReport).AutoFilter Field:=1, Criteria1:=Application.Transpose(IDsArray), Operator:=xlFilterValues

End Sub

I would say I'm a moderately basic user of VBA so please explain any answers. 我会说我是VBA的基本用户,所以请解释所有答案。

Range to filter on 过滤范围

Data to be filtered 要过滤的数据

Desired output 所需的输出

Excel likes it's autofilter arrays as strings. Excel喜欢将它的自动筛选器数组作为字符串。 So you need to convert the array to string values. 因此,您需要将数组转换为字符串值。 Then it works. 然后就可以了。

Sub Test()

    Dim Template As Workbook
    Set Template = ThisWorkbook
    Dim IDs, Report As Worksheet
    Set IDs = Template.Worksheets("IDs")
    Set Report = Template.Worksheets("Report")

    Dim LastRowIDs As Long
    LastRowIDs = IDs.Range("A" & IDs.Rows.Count).End(xlUp).Row

    Dim IDsArray As Variant
    Dim sTemp As String, i As Integer
    IDsArray = Application.Transpose(IDs.Range("A2:A" & LastRowIDs))
    For i = LBound(IDsArray) To UBound(IDsArray)
        sTemp = "," & IDsArray(i) & sTemp
    Next i
    IDsArray = Split(Mid(sTemp, 2), ",")

    Dim LastRowReport As Long
    LastRowReport = Report.Range("A" & Report.Rows.Count).End(xlUp).Row

    Report.AutoFilterMode = False
    Report.Range("A1:C" & LastRowReport).AutoFilter Field:=1, Criteria1:=IDsArray, Operator:=xlFilterValues

End Sub

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

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