如何使用VBA删除每个段落末尾的换行符,然后将这些段落连接起来?

huangapple go评论62阅读模式
英文:

How to remove line break at the end of each paragraph and then join the paragraphs using VBA?

问题

I've translated the code as requested:

Sub 删除行间断()
    Dim rng As Range
    Dim para As paragraph
    
    Set rng = Selection.Range
    
    ' 循环处理范围内的每个段落
    For Each para In rng.Paragraphs
        Debug.Print para.Range.Text
        If Right(para.Range.Text, 1) = vbCr Or Right(para.Range.Text, 1) = vbLf Then
            para.Range.Collapse Direction:=wdCollapseEnd
            para.Range.MoveStart Unit:=wdCharacter, Count:=-1
            para.Range.Delete
        End If
    Next para
End Sub

And for the second part:

Sub 将选定的段落添加到数组()
    Dim selectedParagraphs() As String ' 声明一个数组来存储选定的段落
    Dim paragraph As paragraph ' 用于保存每个选定的段落的变量
    Dim i As Long
      
    ' 调整数组大小以容纳选定的段落
    ReDim selectedParagraphs(1 To Selection.Range.Paragraphs.Count)
    
    ' 循环遍历选定的段落并将它们添加到数组中
    For i = 1 To Selection.Range.Paragraphs.Count
        Set paragraph = Selection.Range.Paragraphs(i)
        paragraph.Range.Collapse Direction:=wdCollapseEnd ' 折叠范围到段落的末尾
        paragraph.Range.MoveEnd Unit:=wdCharacter, Count:=-1 ' 选择换行符
        selectedParagraphs(i) = paragraph.Range.Text
    Next
    
    ' 将数组的元素连接成单个字符串
    Dim joinedText As String
    joinedText = Join(selectedParagraphs, " ")
    
    ' 在消息框中显示连接后的文本
    ' MsgBox joinedText
    Selection.Range.Text = joinedText
End Sub

Please note that if you intend to run this VBA code in Microsoft Word, you may need to adjust it according to your specific Word version and document settings.

英文:

I have the following kind of paragraphs in my Word document:

My name
is
John Doe.

I would like to remove the line breaks at the end of each line and join the lines to achieve the following:

My name is John Doe.

In order to do this, I put together the following VBA code, but it doesn't work. I get a Compile error: Can't find project or library.

Sub removelinebreak()
    Dim rng As Range
    Dim para As paragraph
    
    Set rng = Selection.Range
    
    ' Loop through each paragraph in the range
    For Each para In rng.Paragraphs
        Debug.Print para.Range.text
        If Right(para.Range.text, 1) = vbCr Or Right(para.Range.text, 1) = vbLf Then
            para.Range.Collapse Direction:=wdCollapseEnd
            para.Range.MoveStart Unit: wdCharacter , Count:=-1
            para.Range.Delete
        End If
    Next para
End Sub

Can you please help on where I am going wrong.

Thanks!

UPDATE - DIFFERENT APPROACH - USING ARRAYS

I tried the following approach, but even this does not work.
The output is as follows:

My name
is
John Doe.

It just adds a space before is and John Doe. It does not remove the line breaks.

Sub AddSelectedParagraphsToArray()
    Dim selectedParagraphs() As String ' Declare an array to store the selected paragraphs
    Dim paragraph As paragraph ' Variable to hold each selected paragraph
    Dim i As Long
      
    ' Resize the array to accommodate the selected paragraphs
    ReDim selectedParagraphs(1 To Selection.Range.Paragraphs.Count)
    
    ' Loop through the selected paragraphs and add them to the array
    For i = 1 To Selection.Range.Paragraphs.Count
        Set paragraph = Selection.Range.Paragraphs(i)
        paragraph.Range.Collapse Direction:=wdCollapseEnd 'Collapse the range to the last point of the paragraph
        paragraph.Range.MoveEnd Unit:=wdCharacter, Count:=-1 ' Select the line break
        'selectedParagraphs(i) = Replace(paragraph.Range.text, vbCrLf, " ")
        selectedParagraphs(i) = paragraph.Range.text
    Next
    
    ' Join the elements of the array back into a single string
    Dim joinedText As String
    joinedText = Join(selectedParagraphs, " ")
    
    ' Display the joined text in a message box
    'MsgBox joinedText
    Selection.Range.text = joinedText
End Sub

Based off the help received, the following solutions worked:

Solution 1 - using the Left function

Sub AddSelectedParagraphsToArray()
    Dim selectedParagraphs() As String ' Declare an array to store the selected paragraphs
    Dim paragraph As paragraph ' Variable to hold each selected paragraph
    Dim i As Long
      
    ' Resize the array to accommodate the selected paragraphs
    ReDim selectedParagraphs(1 To Selection.Range.Paragraphs.Count)
    
    ' Loop through the selected paragraphs and add them to the array
    For i = 1 To Selection.Range.Paragraphs.Count
        Set paragraph = Selection.Range.Paragraphs(i)
        selectedParagraphs(i) = VBA.Left(paragraph.Range.text, VBA.Len(paragraph.Range.text) - 1)
    Next
    
    ' Join the elements of the array back into a single string
    Dim joinedText As String
    joinedText = Join(selectedParagraphs, " ")
    
    ' Display the joined text in a message box
    'MsgBox joinedText
    Selection.Range.text = joinedText
End Sub

Solution 2 - using the Replace function

Sub ReplaceSelectedRangeWithJoinedText()
    Dim selectedParagraphs() As String ' Declare an array to store the selected paragraphs
    Dim paragraph As paragraph ' Variable to hold each selected paragraph
    Dim i As Long
    
    ' Resize the array to accommodate the selected paragraphs
    ReDim selectedParagraphs(1 To Selection.Range.Paragraphs.Count)

    ' Loop through the selected paragraphs and add them to the array
    For i = 1 To Selection.Range.Paragraphs.Count
        Set paragraph = Selection.Range.Paragraphs(i)
        selectedParagraphs(i) = paragraph.Range.text
    Next
    
    ' Join the elements of the array back into a single string and replace line breaks with spaces
    Dim joinedText As String
    Dim texttoreplace As String
    joinedText = Join(selectedParagraphs, "")
    texttoreplace = Replace(joinedText, vbCr, " ")
    'joinedText = Replace(Join(selectedParagraphs, ""), vbCr, " ")
    
    ' Replace the selected range with the joined text
    Selection.Range.text = texttoreplace
End Sub

答案1

得分: 1

para.Range.MoveStart Unit:=wdCharacter, Count:=-1

Your code is simply wrong and will clear all contents after execution! Try this code first please:

Sub removelinebreak()
    Dim rng As Range
    Dim para As Paragraph
    
    Dim ur As UndoRecord
    Set ur = Word.Application.UndoRecord
    ur.StartCustomRecord "removelinebreak"
    
    Set rng = Selection.Range
    
    With rng.Find
        .ClearFormatting
        .ClearAllFuzzyOptions
        .Text = vbCr
        .Wrap = wdFindStop
        .Forward = True
        .Execute , , , , , , , , , " ", wdReplaceAll
        .Text = vbLf
        .Execute , , , , , , , , , " ", wdReplaceAll
        .Execute Chr(11), , , , , , , , , " ", wdReplaceAll
        .Execute ". ^p", , , , , , , , , ".^p", wdReplaceAll
        .Execute "  ", , , , , , , , , " ", wdReplaceAll
        .ClearFormatting
        .ClearAllFuzzyOptions
    End With
    ur.EndCustomRecord
    ' Loop through each paragraph in the range
    ' For Each para In rng.Paragraphs
    '     Debug.Print para.Range.Text
    '     If Right(para.Range.Text, 1) = vbCr Or Right(para.Range.Text, 1) = vbLf Then
    '         para.Range.Collapse Direction:=wdCollapseEnd
    '         para.Range.MoveStart Unit:=wdCharacter, Count:=-1
    '         para.Range.Delete
    '     End If
    ' Next para
End Sub

If this is what you want, you can refer to my previous answers:

https://stackoverflow.com/a/76378388/8249058

https://stackoverflow.com/a/76392401/8249058

UPDATE - DIFFERENT APPROACH - USING ARRAYS

Sub AddSelectedParagraphsToArray()
    Dim selectedParagraphs() As String ' Declare an array to store the selected paragraphs
    Dim paragraph As Paragraph ' Variable to hold each selected paragraph
    Dim i As Long
    
    Dim ur As UndoRecord
    Set ur = Word.Application.UndoRecord
    ur.StartCustomRecord "AddSelectedParagraphsToArray"
      
    ' Resize the array to accommodate the selected paragraphs
    ReDim selectedParagraphs(1 To Selection.Range.Paragraphs.Count)
    
    ' Loop through the selected paragraphs and add them to the array
    For i = 1 To Selection.Range.Paragraphs.Count
        Set paragraph = Selection.Range.Paragraphs(i)
        ' paragraph.Range.Collapse Direction:=wdCollapseEnd 'Collapse the range to the last point of the paragraph
        ' paragraph.Range.MoveEnd Unit:=wdCharacter, Count:=-1 ' Select the line break
        'selectedParagraphs(i) = Replace(paragraph.Range.text, vbCrLf, " ")
        ' this is the point!!! the last character is still vbcr (ie. chr(13), "^p", etc.)
        'selectedParagraphs(i) = paragraph.Range.Text
        selectedParagraphs(i) = VBA.Left(paragraph.Range.Text, VBA.Len(paragraph.Range.Text) - 1)
    Next
    
    ' Join the elements of the array back into a single string
    Dim joinedText As String
    joinedText = Join(selectedParagraphs, " ")
    
    ' Display the joined text in a message box
    'MsgBox joinedText
    Selection.Range.Text = joinedText
    
    ur.EndCustomRecord
End Sub
英文:
para.Range.MoveStart Unit: wdCharacter , Count:=-1

Should be :

para.Range.MoveStart Unit:= wdCharacter , Count:=-1

Your code is simply wrong and will clear all contents after execution! Try this code first plz:

Sub removelinebreak()
    Dim rng As Range
    Dim para As Paragraph
    
    Dim ur As UndoRecord
    Set ur = Word.Application.UndoRecord
    ur.StartCustomRecord "removelinebreak"
    
    Set rng = Selection.Range
    
    With rng.Find
        .ClearFormatting
        .ClearAllFuzzyOptions
        .Text = vbCr
        .Wrap = wdFindStop
        .Forward = True
        .Execute , , , , , , , , , " ", wdReplaceAll
        .Text = vbLf
        .Execute , , , , , , , , , " ", wdReplaceAll
        .Execute Chr(11), , , , , , , , , " ", wdReplaceAll
        .Execute ". ^p", , , , , , , , , ".^p", wdReplaceAll
        .Execute "  ", , , , , , , , , " ", wdReplaceAll
        .ClearFormatting
        .ClearAllFuzzyOptions
    End With
    ur.EndCustomRecord
'    ' Loop through each paragraph in the range
'    For Each para In rng.Paragraphs
'        Debug.Print para.Range.Text
'        If Right(para.Range.Text, 1) = vbCr Or Right(para.Range.Text, 1) = vbLf Then
'            para.Range.Collapse Direction:=wdCollapseEnd
'            para.Range.MoveStart Unit:=wdCharacter, Count:=-1
'            para.Range.Delete
'        End If
'    Next para
End Sub

If this is what you want, you can refer to my previous answers:
<https://stackoverflow.com/a/76378388/8249058>

<https://stackoverflow.com/a/76392401/8249058>

UPDATE - DIFFERENT APPROACH - USING ARRAYS

Sub AddSelectedParagraphsToArray()
    Dim selectedParagraphs() As String &#39; Declare an array to store the selected paragraphs
    Dim paragraph As paragraph &#39; Variable to hold each selected paragraph
    Dim i As Long
    
    Dim ur As UndoRecord
    Set ur = Word.Application.UndoRecord
    ur.StartCustomRecord &quot;AddSelectedParagraphsToArray&quot;
      
    &#39; Resize the array to accommodate the selected paragraphs
    ReDim selectedParagraphs(1 To Selection.Range.Paragraphs.Count)
    
    &#39; Loop through the selected paragraphs and add them to the array
    For i = 1 To Selection.Range.Paragraphs.Count
        Set paragraph = Selection.Range.Paragraphs(i)
&#39;        paragraph.Range.Collapse Direction:=wdCollapseEnd &#39;Collapse the range to the last point of the paragraph
&#39;        paragraph.Range.MoveEnd Unit:=wdCharacter, Count:=-1 &#39; Select the line break
        &#39;selectedParagraphs(i) = Replace(paragraph.Range.text, vbCrLf, &quot; &quot;)

        rem this is the point!!! the last character is still vbcr (ie. chr(13), &quot;^p&quot;, etc.)
        &#39;selectedParagraphs(i) = paragraph.Range.Text
        selectedParagraphs(i) = VBA.Left(paragraph.Range.Text, VBA.Len(paragraph.Range.Text) - 1)
    Next
    
    &#39; Join the elements of the array back into a single string
    Dim joinedText As String
    joinedText = Join(selectedParagraphs, &quot; &quot;)
    
    &#39; Display the joined text in a message box
    &#39;MsgBox joinedText
    Selection.Range.Text = joinedText
    
    ur.EndCustomRecord
End Sub

huangapple
  • 本文由 发表于 2023年6月15日 15:55:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76480278.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定