清除Docx VBA中的新行

时间:2013-07-29 15:02:02

标签: vba docx

我需要删除所有新行,如果是连续的,我知道excel中的宏但不是单词,我怎么能读取整行的值?

我用以下内容阅读了文档中的所有行:

For i = 1 To 10
    Selection.MoveDown Unit:=wdLine, Count:=1
Next i

是否有其他方法可以读取每一行或如何知道单词中的总行数以便将其放入for?

由于

1 个答案:

答案 0 :(得分:1)

  

如果是连续的话,我需要删除所有新行

每个空行实际上是一个段落,所以:

Sub RemoveBlankParas()
    Dim para As Paragraph

    For Each para In ActiveDocument.Paragraphs
        If Len(para.Range.Text) = 1 Then
            'only the paragraph mark, so..
            para.Range.Delete
        End If
    Next para
End Sub

但是,如果只有两个连续的空白段落,那么使用ReplaceAll会更容易,更快捷。这是一个可以整理的录制宏:

Sub Macro2()
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "^p^p"
        .Replacement.Text = "^p"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub

Word的“查找/替换”功能使用正则表达式的原始形式,因此以下内容会减少两个或多个连续的段落标记。 NB MatchWildcards = True使用正则表达式:

Sub Macro2()
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "(^13)\1@"
        .Replacement.Text = "^p"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchWildcards = True
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub

Word regular expressions