反转表以准备VLOOKUP

时间:2015-02-16 10:41:26

标签: excel excel-vba excel-formula excel-2010 vba

我有一张非常长的桌子,看起来像这样

123 | ABC
123 | EFG
123 | HIJ
456 | KLM
456 | NOP

我需要它看起来像这样

123 | ABC | EFG | HIJ
456 | KLM | NOP

如何在Excel 2010中执行此操作?

任何帮助将不胜感激!

亲切的问候 丹尼尔

1 个答案:

答案 0 :(得分:0)

这应该完成工作。它假定数据按列A排序。此代码将新表放在工作表2上。

Sub fun()
    Dim lastRow As Integer
    Dim lastCol As Integer
    Dim newSorter As Integer
    Dim oldSorter As Integer
    Dim i As Integer
    Dim newRow As Integer

    oldSorter = 0
    newRow = 1

    lastRow = Sheets(1).Cells(6000, 1).End(xlUp).Row

    For i = 1 To lastRow

        newSorter = Sheets(1).Cells(i, 1).Value
        If newSorter = oldSorter Then 'Add item to right of last entry
            lastCol = Sheets(2).Cells(newRow - 1, 50).End(xlToLeft).Column 'Find last column
            Sheets(2).Cells(newRow - 1, lastCol + 1) = Sheets(1).Cells(i, 2).Value

        Else 'Create new row
            Sheets(2).Cells(newRow, 1) = Sheets(1).Cells(i, 1).Value
            Sheets(2).Cells(newRow, 2) = Sheets(1).Cells(i, 2).Value
            newRow = newRow + 1
        End If
        oldSorter = newSorter
    Next i

End Sub