繁体   English   中英

Excel 根据另一列中的值筛选列表

[英]Excel filter a list based on a value in another column

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

例子:

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

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

我怎样才能做到这一点?

确保将“标题”行作为第一个行,然后您可以使用 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

暂无
暂无

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

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