excel row以逗号分隔

时间:2013-03-24 12:25:28

标签: excel excel-vba xls xlsx vba

我有一个xls文件,其值如下:

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

我想将其转换为(创建新工作表)

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

基本上,我希望所有具有相同ID的行都以逗号分隔的方式连接所有值。

谢谢,

1 个答案:

答案 0 :(得分:2)

尝试以下代码:

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