Excel VBA - 根据第一个单元格值对范围内的每一行进行操作

Excel VBA - Act on each row in a range based on first cell value

我有一个包含多行的工作表,每行都有相同的字段。第一列包含一个组 ID。每行可能有一个不同的组,并且它们混在一起。可能有任意数量的不同组 ID。我想遍历范围,并针对每个组 ID 对该行执行一个操作。

Group   ID
A   d001
A   d002
B   d003
A   d004
B   d005
C   d006
B   d007
C   d008

输出类似于:

Group A:
d001
d002
d004
Group B:
d003
d005
d007
Group C:
d006
d008

这似乎是一个 SQL 'WHERE" 语句。在此先感谢。

使用这个

Sub test()
Dim oCell As Range, i&, LRow&, KeyGR As Variant, KeyIdGr
Dim Group As Object: Set Group = CreateObject("Scripting.Dictionary")
Dim IdGroup As Object: Set IdGroup = CreateObject("Scripting.Dictionary")
i = 1
LRow = Cells(Rows.Count, "A").End(xlUp).Row
For Each oCell In Range("A2:A" & LRow)
    If Not Group.exists(oCell.Value) And oCell.Value <> "" Then
        Group.Add oCell.Value, i: i = i + 1
    End If
Next
For Each oCell In Range("B2:B" & LRow)
    If Not Group.exists(oCell.Value) And oCell.Value <> "" Then
        IdGroup.Add oCell.Value, oCell.Offset(, -1).Value
    End If
Next
i = 1
For Each KeyGR In Group
    Cells(i, "C").Value = "Group " & KeyGR & ":"
    i = i + 1
    For Each KeyIdGr In IdGroup
        If IdGroup(KeyIdGr) = KeyGR Then
            Cells(i, "C").Value = KeyIdGr
            i = i + 1
        End If
    Next
Next
End Sub

最终结果