2

一列中的某些单元格包含多个以逗号分隔的项目。

我想要所有项目的一行。

这是一个例子:

原来的: 图1

应该: 图2

4

3 回答 3

4

正如 jswolf19 所提到的,您可以使用该SPLIT函数将分隔字符串转换为数组。然后,只需遍历数组中的项目并根据需要插入新行。

下面的过程应该可以帮助您入门。

我假设您的数据在 A:E 列中,并使用rng变量进行设置。根据需要进行修改。

根据 OP 评论修改代码

Sub SplitPartsRows()
Dim rng As Range
Dim r As Long
Dim arrParts() As String
Dim partNum As Long
'## In my example i use columns A:E, and column D contains the Corresponding Parts ##

Set rng = Range("A1:BI13876") '## Modify as needed ##'

r = 2
Do While r <= rng.Rows.Count
    '## Split the value in column BB (54) by commas, store in array ##
    arrParts = Split(rng(r, 54).Value, ",")
    '## If there's more than one item in the array, add new lines ##
    If UBound(arrParts) >= 1 Then '## corrected this logic for base 0 array
        rng(r, 54).Value = arrParts(0)

        '## Iterate over the items in the array ##
        For partNum = 1 To UBound(arrParts)
            '## Insert a new row ##'
            '## increment the row counter variable ##
            r = r + 1
            rng.Rows(r).Insert Shift:=xlDown

            '## Copy the row above ##'
            rng.Rows(r).Value = rng.Rows(r - 1).Value

            '## update the part number in the new row ##'
            rng(r, 54).Value = Trim(arrParts(partNum))

            '## resize our range variable as needed ##
            Set rng = rng.Resize(rng.Rows.Count + 1, rng.Columns.Count)

        Next

    End If
'## increment the row counter variable ##
r = r + 1
Loop

End Sub
于 2013-05-14T15:18:36.653 回答
1

试试这个宏:

Sub mcrSplit_and_Insert()
    Dim i As Long, r As Long, rws As Long, c As Range, vC As Variant
    On Error GoTo FallThrough
    Application.EnableEvents = False
    Application.ScreenUpdating = False

    For r = Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1
        If InStr(1, Cells(r, 4).Value, ",") > 0 Then
            rws = Len(Cells(r, 4).Value) - Len(Replace(Cells(r, 4).Value, ",", vbNullString))
            Cells(r + 1, 4).Resize(rws, 1).EntireRow.Insert
            Cells(r, 1).Resize(rws + 1, 9).FillDown
            For i = 0 To rws
                For Each c In Cells(r + i, 1).Resize(1, 9)
                    If InStr(1, c.Value, ",") > 0 Then
                        vC = Split(c.Value, ",")
                        c = vC(i)
                    End If
                    If IsNumeric(c) Then c = c.Value
                Next c
            Next i
        End If
    Next r
    Columns(2).NumberFormat = "m/d/yy"
FallThrough:
    Application.ScreenUpdating = True
    Application.EnableEvents = True
End Sub
于 2014-03-03T11:41:15.003 回答
0

这也可以通过以下方式完成:

  1. 数据 - 导入自;

  2. 在查询模式中导入源后,右键单击所需的列并选择“拆分列”。

  3. 在对话框中单击“高级”并将拆分模式从列更改为行。

于 2019-11-24T13:49:02.313 回答