1

我有看起来像这样的数据:

BOB  | 4
BOB  | 3
BOB  | 7
MARY | 1
JOE  | 2
JOE  | 1
MIKE | 6

我想最终得到如下所示的数据:

BOB  | 4 | 3 | 7
MARY | 1 |   |
JOE  | 2 | 1 |
MIKE | 6 |   |

问题是,我如何解释名称出现的可变次数?

4

2 回答 2

2

我想出了以下代码。感觉它可以更清洁。

这适用于工作表上任何选定的数据块(假设它是预先排序的)。它在同一区域的同一张纸上输出。

Sub WrapDuplicates()
    Dim data(), i As Long, startCell As Range, rwCnt As Long, col As Long

    data = Selection //pull selected data into an array
    Set startCell = Selection.Cells(1, 1) //Get reference to write results to
    Selection.ClearContents //remove original data
    startCell = data(1, 1) //Output first name
    startCell.Offset(0, 1) = data(1, 2) //Output first value

    rwCnt = 0
    col = 2

    For i = 2 To UBound(data) //Loop through array and check if name is same or not and output accordingly
        If data(i, 1) = data(i - 1, 1) Then
            startCell.Offset(rwCnt, col) = data(i, 2)
            col = col + 1
        Else
            rwCnt = rwCnt + 1
            col = 2
            startCell.Offset(rwCnt, 0) = data(i, 1)
            startCell.Offset(rwCnt, 1) = data(i, 2)
        End If
    Next i
End Sub
于 2011-05-10T17:07:32.160 回答
0

我假设您想根据帖子中的 excel-vba 标签在代码中执行此操作。

我还假设数据按名称排序,或者您可以在代码执行之前按名称排序。

源在表 1 中,目标在表 2 中。代码在 Excel VBA 中。我使用您的示例数据进行了测试,将这个子例程放在 Excel 代码隐藏的 ThisWorkbook 部分并按下播放键。

目标标头每次都会被重写,从性能的角度来看这并不理想,但我认为这不是问题。您可以将其包装在 if 语句中,如果它成为问题,则检查目标列 index = 2。

Sub ColumnsToRows()

Dim rowHeading
Dim previousRowHeading
Dim sourceRowIndex
Dim targetRowIndex
Dim targetColumnIndex


sourceRowIndex = 1
targetRowIndex = 1
targetColumnIndex = 2

rowHeading = Sheet1.Cells(sourceRowIndex, 1)
previousRowHeading = rowHeading

While Not rowHeading = ""

    If Not previousRowHeading = rowHeading Then
        targetRowIndex = targetRowIndex + 1
        targetColumnIndex = 2
    End If

    Sheet2.Cells(targetRowIndex, 1) = rowHeading
    Sheet2.Cells(targetRowIndex, targetColumnIndex) = Sheet1.Cells(sourceRowIndex, 2)
    previousRowHeading = rowHeading

    sourceRowIndex = sourceRowIndex + 1
    targetColumnIndex = targetColumnIndex + 1
    rowHeading = Sheet1.Cells(sourceRowIndex, 1)

Wend

End Sub

我是开发人员,而不是 Excel 专家。可能有一些 Excel 函数、数据透视表或其他一些 Excel 魔术可以自动为您执行此操作。

于 2011-05-10T16:21:46.340 回答