Excel根据另一列

时间:2017-01-28 14:58:09

标签: excel vba

我使用VBA并且我想返回属于特定ID的项目列表,如何根据该列表过滤列表?

示例:

Col A | Col B
1       Apple
1       Banana
2       Apple
3       Apple
1       Coconut

如果我要求过滤A列= 1的B列值,我会得到{Apple,Banana,Coconut}

我该怎么做?

1 个答案:

答案 0 :(得分:0)

一定要有一个"标题"将行作为第一行,然后您可以使用AutoFilter(),如下所示:

Option Explicit

Sub main()
    Dim vals As Variant

    vals = GetValues(1) '<--| get the array with values corresponding to ID=1
End Sub

使用以下功能:

Function GetValues(ID As Variant) As Variant
    Dim iVal As Long
    Dim cell As Range

    With Range("A1", Cells(Rows.Count, 1).End(xlUp))
        .AutoFilter Field:=1, Criteria1:=ID
        If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then
            With .Resize(.Rows.Count - 1).Offset(1).SpecialCells(xlCellTypeVisible)
                ReDim vals(1 To .Count)
                For Each cell In .Cells
                    iVal = iVal + 1
                    vals(iVal) = cell.Offset(, 1).Value
                Next
            End With
            GetValues = vals
        End If
        .Parent.AutoFilterMode = False
    End With
End Function