在Excel中使用分隔符将单元格拆分为多行

时间:2019-05-20 15:41:53

标签: excel vba

我有两栏。列A具有唯一标识符,列B具有带有定界符的值。需要将A列中的值与B列中的每个值配对。

enter image description here

原始工作表

enter image description here

所需结果

1 个答案:

答案 0 :(得分:0)

解决方案: 对A列进行排序。然后从“开发人员”选项卡中调出VBA编辑器并使用下面的代码。

Sub splitter()
    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, "A").End(xlUp).Row
    Set rng = Range("A2:A" & Lstrw)

    For Each c In rng.Cells
        Set SpltRng = c.Offset(, 1)
        txt = SpltRng.Value
        Orig = Split(txt, "|")

        For i = 0 To UBound(Orig)
            Cells(Rows.Count, "D").End(xlUp).Offset(1) = c
            Cells(Rows.Count, "D").End(xlUp).Offset(, 1) = Orig(i)
        Next i
    Next c
End Sub

最终结果是:

enter image description here

您可以仅使用以下内容来代替第二个循环

With Cells(Rows.Count, "D").End(xlUp).Offset(1).Resize(UBound(Orig) + 1)
    .Value2 = c.Value2
    .Offset(0, 1).Value2 = Application.Transpose(Orig)
End With