你可以试试这个。它正在使用一个dictionary
对象。此解决方案假定每一行都以Row 1 - ID123 / Bob / James
模式开头。
Option Explicit
Sub mergeDuplicates()
Dim d As Object
Dim rng As Range
Dim vArr As Variant
Dim i As Integer, j As Integer
Set rng = Sheets(3).Range("A2:H5")
Set d = CreateObject("Scripting.Dictionary")
vArr = rng.Value
For i = LBound(vArr) To UBound(vArr)
If Not d.Exists(vArr(i, 2)) Then '-- check for unique ID
d.Add vArr(i, 2), Trim(Replace(vArr(i, 1), "-", ""))
For j = 2 To UBound(vArr, 2)
d.Item(vArr(i, 2)) = d.Item(vArr(i, 2)) + "/" & Trim(Replace(vArr(i, j), "/", ""))
Next j
Else
For j = 5 To UBound(vArr, 2)
d.Item(vArr(i, 2)) = d.Item(vArr(i, 2)) + "/" & Trim(Replace(vArr(i, j), "/", ""))
Next j
End If
Next i
'-- output to sheet
rng.Offset(5).Resize(UBound(d.items) + 1, 1) = Application.Transpose(d.items)
'-- split the text to columns
rng.Offset(5).Resize(UBound(d.items) + 1, 1).TextToColumns Destination:= _
rng.Offset(5), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, _
Tab:=True, Semicolon:=False, Comma:=False, Space:=False, _
Other:=True, OtherChar:="/"
Set d = Nothing
End Sub
输出:
根据 OP 的评论和更新
for loop
根据他的真实数据更改内容以适应。
For i = LBound(vArr) To UBound(vArr)
If Not d.Exists(vArr(i, 1)) Then '-- check for unique ID
d.Add vArr(i, 1), Trim(vArr(i, 1)) '-- add RowID as first element in item
For j = 2 To UBound(vArr, 2) '-- then append each element(column) to the first element
d.Item(vArr(i, 1)) = d.Item(vArr(i, 1)) + "/" & Trim(Replace(vArr(i, j), "/", ""))
Next j
Else
For j = 4 To UBound(vArr, 2) '-- when duplicates found, append from 4th column
d.Item(vArr(i, 1)) = d.Item(vArr(i, 1)) + "/" & Trim(Replace(vArr(i, j), "/", ""))
Next j
End If
Next i
基于 OP 更新的样本数据的输出: