vba - 如何使用 Excel VBA 拆分和重组单元格

标签 vba excel

我当前使用的代码拆分:

Original Data

并将其更改为:

Modified Data

但是,这是我要求数据采用的格式:

Required Format

这是我当前代码的副本:

Sub SplitCells()
Dim rColumn As Range
Dim lFirstRow As Long
Dim lLastRow As Long
Dim lRow As Long
Dim lLFs As Long

Set rColumn = Columns("D")
lFirstRow = 1
lLastRow = rColumn.Cells(Rows.Count).End(xlUp).Row

For lRow = lLastRow To lFirstRow Step -1
    lLFs = Len(rColumn.Cells(lRow)) - Len(Replace(rColumn.Cells(lRow), vbLf, ""))
    If lLFs > 0 Then
        rColumn.Cells(lRow + 1).Resize(lLFs).EntireRow.Insert xlShiftDown
        rColumn.Cells(lRow).Resize(lLFs + 1).Value = Application.Transpose(Split(rColumn.Cells(lRow), vbLf))
    End If
Next lRow
End Sub

任何帮助/评论将不胜感激。

最佳答案

在代码末尾调用 ResizeToFit

在当前代码中的 End Sub 之前添加 ResizeToFit

即。

...
Next lRow
ResizeToFit ' or Call ResizeToFit
End Sub
...

将此代码作为新子添加到同一模块中

Sub ResizeToFit()
Application.ScreenUpdating = False

    Dim i As Long
    For i = Range("D" & Rows.Count).End(xlUp).Row To 1 Step -1
        If IsEmpty(Range("D" & i)) Then
            Rows(i & ":" & i).Delete
        Else
            Range("E" & i) = Split(Range("D" & i), Chr(32))(1)
            Range("D" & i) = Split(Range("D" & i), Chr(32))(0)
        End If
    Next i

    For i = 1 To 5
        If i <> 4 Then
            Cells(1, i).Resize(Range("D" & Rows.Count).End(xlUp).Row, 1).Value = Cells(1, i)
        End If
    Next

Application.ScreenUpdating = True
End Sub

拿这个

enter image description here

运行我的代码会产生

enter image description here

关于vba - 如何使用 Excel VBA 拆分和重组单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20564820/

相关文章:

excel - 在 vba 上将值粘贴到另一个工作簿工作表上时出现问题

vba - 在 VBA 中使用 powerpoint 的撤消命令

python - 如何使用 openpyxls 将数据表添加到图表空间?

vba - 如何使用 VBA 限制图表的源数据?

vba - 平均公式 Excel VBA

excel - 错误 2147217904 从 Excel 查询 Access 时没有为一个或多个必需参数提供值

excel - Power BI 高级日期筛选

vba - 更改 VBA 中的小数点分隔符

excel - 从 Excel 中的文本单元格中提取 URL

c# - NPOI 写入 XLS 而不是 XLSX