以下代码要求您添加对“Microsoft Scripting Runtime”的引用。
VBA Editor->Tools->References, Find and select Microsoft Scripting Runtime
它可以使用“集合”而不是“字典”。我只是更喜欢字典。
代码将读取活动工作表(“Do Loop”)并复制数据(删除过程中的重复项)
然后它会清除工作表上的所有数据。
然后它遍历收集的数据并将其输出到现在为空的工作表(“For Each”循环)
Sub Cat()
Dim Data As Dictionary
Dim Sheet As Worksheet
Set Sheet = ThisWorkbook.ActiveSheet
Set Data = New Dictionary
Dim Row As Integer
Dim Key As Variant
Dim Keys() As Variant
Dim Value As Variant
Dim Values() As Variant
Dim List As String
Row = 1
Do
If Data.Exists(CStr(Sheet.Cells(Row, 1))) Then
If Not Data(CStr(Sheet.Cells(Row, 1))).Exists(CStr(Sheet.Cells(Row, 2))) Then
Data(CStr(Sheet.Cells(Row, 1))).Add (CStr(Sheet.Cells(Row, 2))), True
End If
Else
Data.Add CStr(Sheet.Cells(Row, 1)), New Dictionary
Data(CStr(Sheet.Cells(Row, 1))).Add (CStr(Sheet.Cells(Row, 2))), True
End If
Row = Row + 1
If IsEmpty(Sheet.Cells(Row, 1)) Then
Exit Do
End If
Loop
Sheet.Cells.ClearContents
Keys = Data.Keys
Row = 1
For Each Key In Keys
Values = Data(Key).Keys
Sheet.Cells(Row, 1) = Key
List = ""
For Each Value In Values
If List = "" Then
List = Value
Else
List = List & ", " & Value
End If
Next Value
Sheet.Cells(Row, 2) = List
Row = Row + 1
Next Key
End Sub