excel row to comma separated

2019-09-21 02:33发布

I have an xls file with values of the following:

ID Value
1 value1
1 value2
1 value3
2 value1
2 value2
3 value1
3 value2

etc

I would like to transform this to (create a new sheet)

ID Values
1 value1,value2,value3
2 value1,value2
3 value1,value2,value3

Basically, I would like all rows that have the same ID to join all values comma separated.

Thanks,

1条回答
▲ chillily
2楼-- · 2019-09-21 02:54

Try below code :

Sub sample()
    Dim i As Integer, j As Integer
    Dim temp As String
    Range("A:A").AdvancedFilter Action:=xlFilterCopy, copytorange:=Range("C1"), unique:=True

    Dim lastRow As Long
    lastRow = Range("C65000").End(xlUp).Row

    j = 1
     For i = 2 To lastRow
        Do Until Cells(j, 2) = ""
            If Trim(Cells(j, 1)) = Trim(Cells(i, 3)) Then
                temp = temp & "," & Cells(j, 2)
            End If
            j = j + 1
        Loop
        Cells(i, 4) = temp
        temp = ""
        j = 1
    Next
End Sub

enter image description here

enter image description here

查看更多
登录 后发表回答