次のコードでは、「MicrosoftScriptingRuntime」への参照を追加する必要があります。
VBA Editor->Tools->References, Find and select Microsoft Scripting Runtime
「辞書」の代わりに「コレクション」を使用することが可能です。私は辞書が好きです。
コードはアクティブなワークシート(「DoLoop」)を読み取り、データをコピーします(プロセス内の重複を削除します)
次に、シート上のすべてのデータをクリアします。
次に、収集したデータをループして、空になったワークシートに出力します(「ForEach」ループ)
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