在选择中查找和替换正在替换整个文档

时间:2017-03-06 15:27:32

标签: vba vbscript ms-word word-vba

我试图遍历不在表格中的所有段落并突出显示文本:

'Iterate All Paragraphs
Dim p
objWord.Options.DefaultHighlightColorIndex = finalColor
For Each p In objDoc.Paragraphs
    p.Range.Select
    If Not objWord.Selection.Information(wdWithInTable) Then
        With objWord.Selection.Range.Find
            .ClearFormatting
            .Highlight = False
            .Forward = True
            .Wrap = wdFindStop
            .Replacement.ClearFormatting
            .Replacement.Highlight = True
          .Execute , , , , , , True, wdFindStop, , , wdReplaceAll
        End With
    End If
Next

条件objWord.Selection.Information(wdWithInTable)工作正常,但是查找/执行正在替换整个文档中所有未突出显示的文本,即使在表格中也是如此。

任何猜测都是为什么?

1 个答案:

答案 0 :(得分:1)

我真的不认为你应该使用Find对象,但是如果你坚持,也许你应该首先将Selection.Range存储在变量中,然后使用它的.Find属性。

我会这样做:

Sub HighlightNonTableParagraphs()
    Dim oDocument As Document
    Dim oParagraph As Paragraph
    Dim oRange As range

    Set oDocument = ActiveDocument

    For Each oParagraph In oDocument.Paragraphs
        With oParagraph.range
            If Not .Information(wdWithInTable) Then
                .HighlightColorIndex = wdBlue
            End If
        End With
    Next
End Sub