将具有重复项的行换行

我有这样的数据:

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 | | 

问题是,如何解释名称显示的可变次数?

我想出了以下代码。 感觉它可能更干净。

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

 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 

我假设你想要在你的文章中使用基于excel-vba标签的代码。

我还假设数据是按名称sorting的,或者在代码执行之前按名称对数据进行sorting即可。

源在表1中,目标在表2中。代码在Excel VBA中。 我用您的示例数据进行了testing,将此子例程放在Excel代码隐藏的ThisWorkbook部分中,然后按播放。

每次都会重写目标头文件,从性能的angular度来看这并不理想,但我认为这不是一个问题。 你可以把它包装在if语句中,如果它成为一个问题,检查目标列索引= 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魔术自动为您执行此操作。