excel - 根据逗号分隔列表插入行

标签 excel vba

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

我想为所有项目占据一行。

这是一个例子:

原文: Pic1

应该是: Pic2

最佳答案

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

关于excel - 根据逗号分隔列表插入行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16546311/

相关文章:

excel - 如何从换行的文本单元格中提取特定的文本行?

Excel OleDb 数据类型

VBA 搜索 '.' 以及它之后的内容

python - 将数据框的每隔 2 列着色为 excel?

string - Excel - 将日期从 yymmdd 转换为 dd/mm/yy

arrays - 删除后下标超出范围

vb.net - Range 类的 AutoFilter 方法在 VB.NET 中失败

excel - 循环内的运行时错误 91(对象变量或未设置 block 变量),但代码在其外工作

javascript - .NET C# 使用 ExcelPackage 通过 JS post 导出到 excel

Excel VBA : How to write column name with commercial at "@" in it