尝试这个:
Sub combineValues()
Dim dic As Dictionary
Dim key, val, i, p, k
Set dic = New Dictionary
For i = 1 To Worksheets(1).Range("A65536").End(xlUp).Row
key = Worksheets(1).Cells(i, 1).Value
val = Worksheets(1).Cells(i, 2).Value
If dic.Exists(key) Then
dic.Item(key) = dic.Item(key) & ", " & val
Else
dic.Add key, val
End If
Next
p = 1
For Each k In dic.Keys
Worksheets(2).Cells(p, 1) = k
Worksheets(2).Cells(p, 2) = dic.Item(k)
p = p + 1
Next
End Sub
请注意,您必须在“参考”中包含“Microsoft 脚本运行时”才能使用Dictionary
.
使用以下 [表 1] 进行测试:
1 value 1
2 value 2
3 value 3
1 value 4
1 value 5
3 value 6
3 value 7
2 value 8
1 value 9
2 value 10
2 value 11
2 value 12
结果如下 [表 2]:
1 value 1, value 4, value 5, value 9
2 value 2, value 8, value 10, value 11, value 12
3 value 3, value 6, value 7