如何在Excel中将单个单元格拆分为多行

时间:2019-11-27 18:31:47

标签: excel vba

我有一个包含六个列的表。我想发生的是将一个单元格(F2)中的整数值分成多行。

此外,我还需要A-E中的行与整数关联。 我在Stack Overflow上找到了一个类似于我需要的VBA,但只有在两列时,它才有效。任何帮助,将不胜感激。注意,多年来我都没有用VBA编写过。

enter image description here

下面是我一直尝试运行的代码

Sub ChickatAH()
    Dim rng As Range, Lstrw As Long, c As Range
    Dim SpltRng As Range
    Dim i As Integer
    Dim Orig As Variant
    Dim txt As String

    Lstrw = Cells(Rows.Count, "F").End(xlUp).Row
    Set rng = Range("A2:F" & Lstrw)

    For Each cell In rng.Cells
        Set SpltRng = cell.Offset(, 1)
        txt = SpltRng.Value
        Orig = Split(txt, Chr(10))
    For i = 0 To UBound(Orig)
        Cells(Rows.Count, "H").End(xlUp).Offset(1) = cell
        Cells(Rows.Count, "H").End(xlUp).Offset(, 1) = Orig(i)
    Next i
Next cell
End Sub

1 个答案:

答案 0 :(得分:0)

修改了此帖子上的代码。它产生了我想要的解决方案。 VBA: Split cell values into multiple rows and keep other data

Sub splitByColF()
    Dim r As Range, i As Long, ar
    Set r = Worksheets("Sheet1").Range("F999999").End(xlUp)
    Do While r.Row > 1
        ar = Split(r.Value, Chr(10))
        If UBound(ar) >= 0 Then r.Value = ar(0)
        For i = UBound(ar) To 1 Step -1
            r.EntireRow.Copy
            r.Offset(1).EntireRow.Insert
            r.Offset(1).Value = ar(i)
        Next
        Set r = r.Offset(-1)
    Loop
End Sub