将Excel数据从重复行转换为非重复列

时间:2016-10-25 16:28:39

标签: excel vba excel-vba

我需要转换以下行列格式。名称以不同的值重复的地方。

Name Value
XYZ   1
XYZ   2
XYZ   3
XYZ   4
XYZ   5
XYZ   6
XYZ   7
ABC   7
ABC   6
ABC   5
ABC   4
ABC   3
ABC   2
ABC   1

我需要转换为这种格式。

XYZ ABC
1   7
2   6
3   5
4   4
5   3
6   2
7   1

提前谢谢

1 个答案:

答案 0 :(得分:1)

尝试使用脚本字典方法。

Option Explicit

Sub reGroup()
    Dim i As Long
    Dim k As Variant, dXYZs As Object

    Set dXYZs = CreateObject("Scripting.Dictionary")
    dXYZs.CompareMode = vbTextCompare

    With Worksheets("Sheet2")
        For i = 2 To .Cells(Rows.Count, "B").End(xlUp).Row
            If dXYZs.exists(.Cells(i, "A").Value2) Then
                dXYZs.Item(.Cells(i, "A").Value2) = _
                  dXYZs.Item(.Cells(i, "A").Value2) & ChrW(8203) & .Cells(i, "B").Value2
            Else
                dXYZs.Item(UCase(.Cells(i, "A").Value2)) = .Cells(i, "B").Value2
            End If
        Next i

        i = 0
        For Each k In dXYZs.keys
            .Cells(1, 4 + i) = k
            .Cells(2, 4 + i).Resize(UBound(Split(dXYZs.Item(k), ChrW(8203))) + 1) = _
                Application.Transpose(Split(dXYZs.Item(k), ChrW(8203)))
            i = i + 1
        Next k

    End With
End Sub

scipting_dictionary