使用 VBA 删除 Word 中的空段落:并非所有空段落都被删除

Jos*_*shG 0 vba ms-word

我写了一个宏来删除文档中的所有空段落,但它表现出奇怪的行为:如果文档的最后有许多空段落,大约有一半会被删除。重复运行宏会逐渐消除空段落,直到只剩下一个空段落。即使有边界条件,需要一行代码删除最后一段,但我还是不明白为什么最后的空段落只删除了一半。谁能解释为什么会发生这种情况以及如何纠正这种行为?顺便说一句,我在网上搜索并看到了许多关于检测段落标记的帖子(^p、^13 等,但只有搜索 vbCr 有效,这是另一个小难题。)

Sub Delete_Empty__Paras_2() 'This macro looks for empty paragraphs and deletes them.
Dim original_num_of_paras_in_doc As Integer
Dim num_of_deleted_paras As Integer

original_num_of_paras_in_doc = ActiveDocument.Paragraphs.Count 'Count the number of paragraphs in the document to start
num_of_deleted_paras = 0 'In the beginning, no paragraphs have been deleted

Selection.HomeKey Unit:=wdStory 'Go to the beginning of the document.
For current_para_number = 1 To original_num_of_paras_in_doc 'Process each paragraph in the document, one by one.
    If current_para_number + num_of_deleted_paras > original_num_of_paras_in_doc Then 'Stop processing paragraphs when the loop has processed every paragraph.
        Exit For
    Else 'If the system just deleted the 3rd paragraph of the document because
        ' it's empty, the next paragraph processed is the 3rd one again,
        'so when we iterate the counter, we have to subtract the number of deleted paragraphs to account for this.
        Set paraRange = ActiveDocument.Paragraphs(current_para_number - num_of_deleted_paras).Range
        paratext = paraRange.Text
        If paratext = vbCr Then 'Is the paragraph empty? (By the way, checking for vbCr is the only method that worked for checking for empty paras.)
            paratext = "" 'Delete the paragraph.
            ActiveDocument.Paragraphs(current_para_number - num_of_deleted_paras).Range.Text = paratext
            num_of_deleted_paras = num_of_deleted_paras + 1 'Iterate the count of deleted paras.
        End If
    End If
Next current_para_number
End Sub
Run Code Online (Sandbox Code Playgroud)

Way*_*unn 5

此代码将删除所有空白段落...

Sub RemoveBlankParas()
    Dim oDoc        As Word.Document
    Dim i           As Long
    Dim oRng        As Range
    Dim lParas      As Long

    Set oDoc = ActiveDocument
    lParas = oDoc.Paragraphs.Count          ' Total paragraph count
    Set oRng = ActiveDocument.Range

    For i = lParas To 1 Step -1
        oRng.Select
        lEnd = lEnd + oRng.Paragraphs.Count                         ' Keep track of how many processed
        If Len(ActiveDocument.Paragraphs(i).Range.Text) = 1 Then
            ActiveDocument.Paragraphs(i).Range.Delete
        End If
    Next i

    Set para = Nothing
    Set oDoc = Nothing
    Exit Sub
End Sub
Run Code Online (Sandbox Code Playgroud)