I'm trying to merge rows that have the same ID. I've got it working, but the order of merging is not respected. It puts the last value of the same ID in first, instead of respecting the row order. Anybody who has a clue how to achieve this?
Input:
ID | Value |
---|---|
101 | |
101 | 325grams |
101 | 500grams |
100 | |
100 | 200 grams |
100 | 1 kilo |
100 | 3 kilo |
Current situation:
ID | Value |
---|---|
101 | 500 grams, 325grams |
100 | 3 kilo, 200 grams, 1 kilo |
Desired solution:
ID | Value |
---|---|
101 | 325 grams, 500 grams |
100 | 200 grams, 1 kilo, 3 kilo |
CODE:
Sub Consolidate_Rows()
Dim xRg As Range
Dim xRows As Long
Dim i As Long, J As Long, K As Long
On Error Resume Next
Set xRg = Application.InputBox("Select Range:", "Consolidate selection", Selection.Address, , , , , 8)
Set xRg = Range(Intersect(xRg, ActiveSheet.UsedRange).Address)
If xRg Is Nothing Then Exit Sub
xRows = xRg.Rows.Count
For i = xRows To 2 Step -1
For J = 1 To i - 1
If xRg(i, 1).Value = xRg(J, 1).Value And J <> i Then
For K = 2 To xRg.Columns.Count
If xRg(J, K).Value <> "" Then
If xRg(i, K).Value = "" Then
xRg(i, K) = xRg(J, K).Value
Else
xRg(i, K) = xRg(i, K).Value & "," & xRg(J, K).Value
End If
End If
Next
xRg(J, 1).EntireRow.Delete
i = i - 1
J = J - 1
End If
Next
Next
ActiveSheet.UsedRange.Columns.AutoFit
End Sub
Thanks a bunch!
EDIT: Changed the table to resemble my data more. Sorting of merged cells should not be based alphabetically, but on row order.