[英]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.