使用可变Excel范围在自动过滤器VBA中使用

时间:2018-11-21 05:49:27

标签: excel vba

我已经搜索了很多东西,尝试了很多不同的东西,但是我无法完成以下工作。

我生成了一系列ID。然后,我想过滤一系列数据以生成仅具有指定ID的过滤输出。但是,无论我如何尝试,经过过滤的输出都只会返回一个空白范围。

请注意:每次运行此过程时,我的ID范围都会有所不同。我提供了一组非常简单的数据来说明我的观点-我的实际数据比我的示例复杂得多。

我目前拥有的代码:

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

我会说我是VBA的基本用户,所以请解释所有答案。

Range to filter on

Data to be filtered

Desired output

1 个答案:

答案 0 :(得分:0)

Excel喜欢将它的自动筛选器数组作为字符串。因此,您需要将数组转换为字符串值。然后就可以了。

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