将多列数据拆分为行

时间:2018-07-27 07:03:02

标签: excel excel-vba split

我有大约1000个唯一的行,其中有要拆分的列。我是VBA的新手,不确定如何将多列拆分为具有ID的行。列中的元素数可以在行之间变化,但同一行中的列数相同。

输入:

+----+---------------+----------+----------+
| id |     col1      |   col2   |   col3   |
+----+---------------+----------+----------+
|  1 | abc, bcd, cde | aa,bb,cc | 1a,2b,3a |
|  2 | abc, ded      | ba,de    | a7,7a    |
|  3 | a,b,c,d       | d,c,d,a  | f,d,s,a  |
+----+---------------+----------+----------+

输出:

+----+------+------+------+
| id | col1 | col2 | col3 |
+----+------+------+------+
|  1 | abc  | aa   | 1a   |
|  1 | bcd  | bb   | 2b   |
|  1 | cde  | cc   | 3a   |
|  2 | abc  | ba   | a7   |
|  2 | ded  | de   | 7a   |
|  3 | a    | d    | f    |
|  3 | b    | c    | d    |
|  3 | c    | d    | s    |
|  3 | d    | a    | a    |
+----+------+------+------+

我们将非常感谢您的帮助!


我不知道为什么将这个链接“ VBA: Split cell values into multiple rows and keep other data”作为先前的答案,但我认为将一列和多列分开是不同的问题。

1 个答案:

答案 0 :(得分:1)

尝试以下代码(代码中的注释):

Sub Expand()
    Dim currentRow As Long, lastRow As Long, table As Variant, i As Long, _
        valuesInOneRowCol1 As Variant, valuesInOneRowCol2 As Variant, valuesInOneRowCol3 As Variant
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row
    currentRow = 2
    'read hwole range to memory and clear the range to fill it with expanded data
    table = Range("A2:D" & lastRow).Value2
    Range("A2:D" & lastRow).Clear
    For i = 1 To lastRow - 1
        'split comma separated lists in each column
        valuesInOneRowCol1 = Split(table(i, 2), ",")
        valuesInOneRowCol2 = Split(table(i, 3), ",")
        valuesInOneRowCol3 = Split(table(i, 4), ",")
        'write all data from one row
        For j = LBound(valuesInOneRowCol1) To UBound(valuesInOneRowCol1)
            Cells(currentRow, 1) = table(i, 1)
            Cells(currentRow, 2) = valuesInOneRowCol1(j)
            Cells(currentRow, 3) = valuesInOneRowCol2(j)
            Cells(currentRow, 4) = valuesInOneRowCol3(j)
            currentRow = currentRow + 1
        Next
    Next
End Sub