查找所有缩进的文本

时间:2019-02-28 09:47:31

标签: vba ms-word text-manipulation

我想查找缩进8个空格的文档中的所有文本。下面的代码应找到这些行,并选择该行以供以后处理。但是,该代码无条件地查找/选择了所有行。怎么了?

每次比赛后我都必须重置查找结果吗?怎么做?

+=

1 个答案:

答案 0 :(得分:0)

我已经修改了一些用于替换空白的代码。该例程查找2个或更多的空格。我添加了一些代码并注释了几行,以便您可以测试并查看它是否满足您的要求。

Sub FindAndReplaceEmptySpaces()
    Dim rng As Word.Range
    Set rng = ActiveDocument.Content
    With rng.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = " {2,}" 'look for 2 or more
        .Replacement.Text = " " 'replace with 1
        .Forward = True
        .Wrap = Word.WdFindWrap.wdFindStop
        .Format = False
        .MatchWildcards = True
        'The following was added to demo the search
        .Execute
        Do While .found
            rng.MoveEnd Word.WdUnits.wdParagraph, Count:=1
            Debug.Print rng.Text
            rng.Collapse Word.WdCollapseDirection.wdCollapseEnd
            .Execute
        Loop
        'end of demo code
    End With
'The following code is commented out. Remove comments and demo code above
'to return to the automatically removing extra blank spaces
'    rng.Find.Execute Replace:=Word.WdReplace.wdReplaceAll
'    rng.Find.ClearFormatting
'    rng.Find.Replacement.ClearFormatting

End Sub