添加到Word文档中的每个特定单词

时间:2018-05-06 12:46:55

标签: vba word-vba

我想添加注释,并为文本中找到的特定单词的每个实例将字体颜色更改为红色。使用Selection.Find我只能将字体颜色更改为红色 - 是否有办法为每个找到的单词添加注释?

Sub WordSearcher(word)
  Selection.Find.ClearFormatting
  Selection.Find.Replacement.ClearFormatting
  Selection.Find.Replacement.Font.Color = wdColorGreen
  With Selection.Find
        .Text = word
        '.Replacement.Text = word
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = True
  End With
  Selection.Find.Execute Replace:=wdReplaceAll
End Sub

我编写了下面的代码,它完成了两件事,但它不是很有效,因为整篇文档需要花费几分钟的时间 - 有没有办法在更合理的时间内完成?

For i = 1 To ActiveDocument.Words.Count
        For j = 0 To UBound(arrWords)
            If Trim(UCase(ActiveDocument.Words(i))) = UCase(arrWords(j)) Then
                ActiveDocument.Words(i).Font.Color = vbRed
                ActiveDocument.Comments.Add ActiveDocument.Range(ActiveDocument.Words(i).Start, ActiveDocument.Words(i).End), arrComments(j)
            End If
        Next j
Next

1 个答案:

答案 0 :(得分:1)

是的,这是可能的。它涉及在每个"发现"中断查找。为了添加评论。为了有效地执行此操作,最好使用Range对象,而不是使用Selection

当查找成功时,Find.Execute方法返回布尔值:true。您可以使用它来测试是否应插入注释,以及知道代码何时停止。

请注意,使用Find.Wrap = wdFindStop来避免代码循环非常重要#34;

Sub FindRedAndComment()
    Dim rngFind As word.Range
    Dim doc As word.Document
    Dim sFindText As String
    Dim sCommentText As String
    Dim bFound As Boolean

    Set doc = ActiveDocument
    Set rngFind = doc.content
    sFindText = "test"
    sCommentText = "comment"
    With rngFind.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Replacement.Font.Color = wdColorRed
        .Text = sFindText
        .Forward = True
        .wrap = wdFindStop
        .Format = True
        .MatchCase = False
        .MatchWholeWord = True
        bFound = .Execute(Replace:=wdReplaceOne)
  End With
  Do Until Not bFound
      If bFound Then
        doc.Comments.Add rngFind, sCommentText
        rngFind.Collapse wdCollapseEnd
        rngFind.End = doc.content.End
        bFound = rngFind.Find.Execute(Replace:=wdReplaceOne)
      End If
  Loop
End Sub