首页 > 解决方案 > 从一个单元格创建多行

问题描述

在此处输入图像描述

在此处输入图像描述

大家好,如何使用下面的代码来实现如上图所示的截图?因此,如果它尝试拆分单元格,我希望它能够创建新行。

Sub SplitCellValue()
    Dim str As String
    Dim ArrStr() As String

    'Fill variables: str is the value of the active cell, ArrStr splits this value at the comma
    str = ActiveCell.Value
    ArrStr = Split(str, ", ")

    'Loop through each ArrStr to populate each cell below the activecell

    For i = 0 To UBound(ArrStr)
        ActiveCell.Offset(i, 0).Value = ArrStr(i)
    Next i
    End Sub

标签: excelvba

解决方案


在现有循环中添加一个附加For...Next循环以添加行。包含并If使用布尔值声明来确定是否添加了行(因此是否需要添加)。

这只会为活动单元格的列插入一个新行。

就像是:

'Loop through each ArrStr to populate each cell below the activecell
Dim i As Long
Dim y As Long
Dim RowsAdded As Boolean

RowsAdded = False

For i = 0 To UBound(ArrStr)
    ActiveCell.Offset(i, 0).Value = ArrStr(i)
    If RowsAdded = False Then
        For y = 1 To UBound(ArrStr)
            ActiveCell.Offset(1, 0).EntireRow.Insert xlDown
        Next y
        RowsAdded = True
    End If
Next i

以下是代码执行前后的图片:

前:

代码执行前

后:

代码执行后


推荐阅读