excel - 将换行后的每个单词分成新行

标签 excel vba

我的循环似乎创建了无限行并且出现了问题

For Each Cell In Workbooks(newBook).Sheets(1).Range("A1:A" & lRow)
    Checker = Cell.Value
    For Counter = 1 To Len(Checker)
        If Mid(Checker, Counter, 1) = vbLf Then
            holder = Right(Mid(Checker, Counter, Len(Checker)), Len(Checker))
            Workbooks(newBook).Sheets(1).Range(Cell.Address).EntireRow.Insert
        End If
    Next
Next Cell

最佳答案

使用反向循环。 对于 i = lRow 到 1 Step -1。另外,为了分隔单词,您可以使用 SPLIT()

这就是你正在尝试的吗?

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long
    Dim i As Long, j As Long
    Dim Ar As Variant
    
    '~~> Change this to the relevant worksheet
    Set ws = Sheet2
    
    With ws
        '~~> Find last row in Column A
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row
        
        '~~> Reverse Loop in Column A
        For i = lRow To 1 Step -1
            '~~> Check if cell has vbLf
            If InStr(1, .Cells(i, 1).Value, vbLf) Then
                '~~> Split cell contents
                Ar = Split(.Cells(i, 1).Value, vbLf)
                
                '~~> Loop through the array from 2nd position
                For j = LBound(Ar) + 1 To UBound(Ar)
                    .Rows(i + 1).Insert
                    .Cells(i + 1, 1).Value = Ar(j)
                Next j
                
                '~~> Replace cells contents with content from array from 1st position
                .Cells(i, 1).Value = Ar(LBound(Ar))
            End If
        Next i
    End With
End Sub

之前

enter image description here

之后

enter image description here

关于excel - 将换行后的每个单词分成新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75168130/

相关文章:

excel - 为什么 Excel 将 `=10**-2` 转换为 `=0.1` ?

vba - 在单元格 VBA 中创建指向工作表的超链接

java - Windows 7 java中的权限批量无法识别

excel - 如何找到一个值而不是使用 IF 函数

vba - 子程序填写范围内的值?

vba - 在Excel vba中更改注释大小相对于填充图片的原始大小

ms-access - 在 Access 中制作自定义切换按钮

vba - 在Word中使用VBA,如何找到特定的文本并在大纲中继续编号

excel - 忽略列中的零

excel - 在 VBA Excel 上有 2 种方法处理 "ClearContents",但其中 1 种工作正常。为什么?