Word VBA:查找一组单词并插入预定义注释

Word VBA:查找一组单词并插入预定义注释,vba,ms-word,Vba,Ms Word,我需要自动将注释插入word文档:搜索一组预定义的单词(有时是单词字符串,并且所有单词都不区分大小写),并在每个单词中添加预定义的注释 有两个词集,有两个目标: 单词集1:每个定位的单词都有相同的注释 单词集2:个人评论(我建议基于已识别单词的新文本) 我一直在用一个代码半自动地识别所有识别的单词并突出显示它们,帮助我完成这个过程(但我仍然需要手动输入所有注释-我也能够输入注释-但一次只能输入一个单词。)因为我的VBA技能有限,不幸的是,我试图从具有类似目的的其他代码中编译出一个健壮的宏,结

我需要自动将注释插入word文档:搜索一组预定义的单词(有时是单词字符串,并且所有单词都不区分大小写),并在每个单词中添加预定义的注释

有两个词集,有两个目标:

  • 单词集1:每个定位的单词都有相同的注释
  • 单词集2:个人评论(我建议基于已识别单词的新文本)
我一直在用一个代码半自动地识别所有识别的单词并突出显示它们,帮助我完成这个过程(但我仍然需要手动输入所有注释-我也能够输入注释-但一次只能输入一个单词。)因为我的VBA技能有限,不幸的是,我试图从具有类似目的的其他代码中编译出一个健壮的宏,结果一无所获

下面是我一直在使用的代码

Sub HighlightWordList()

Dim range As range
Dim i As Long
Dim TargetList

TargetList = Array("word1", "word2", "word3")

For i = 0 To UBound(TargetList)

Set range = ActiveDocument.range

With range.Find
.Text = TargetList(i)
.Format = True
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False

Do While .Execute(Forward:=True) = True
range.HighlightColorIndex = wdYellow

Loop

End With
Next

End Sub
下面的代码可以让我直接插入气泡

Sub CommentBubble()
'
'
Dim range As range
Set range = ActiveDocument.Content

Do While range.Find.Execute("Word x") = True
    ActiveDocument.Comments.Add range, "my comment to enter in the bubble"
Loop
End Sub
我试图通过如下所示的方式让流程重复,但我确信,你们中的许多人(我完全不知道)都明白这一点——这一策略失败了,只适用于“word x”,但无法适用于所有后续单词:

Sub CommentBubble()
'
'
Dim range As range
Set range = ActiveDocument.Content

Do While range.Find.Execute("Word x") = True
    ActiveDocument.Comments.Add range, "my 1st comment to enter in the bubble"
Loop

Do While range.Find.Execute("Word y") = True
    ActiveDocument.Comments.Add range, "my 2nd comment to enter in the bubble"
Loop

End Sub
我已经混合和匹配了这些代码的位,但没有用。有什么办法可以帮我使用这两个词集吗

谢谢大家的帮助


向贝诺特致意,你就快到了!您所需要做的就是在第一次循环后重新定义范围对象(因为在该点上它将被耗尽)。像这样:

Sub CommentBubble()
    Dim rng As range
    Set rng = ActiveDocument.Content

    Do While rng.Find.Execute("Word x") = True
        ActiveDocument.Comments.Add rng, "my 1st comment to enter in the bubble"
    Loop

    Set rng = ActiveDocument.Content ' <---------------Add This.

    Do While rng.Find.Execute("Word y") = True
        ActiveDocument.Comments.Add rng, "my 2nd comment to enter in the bubble"
    Loop
End Sub
Sub-CommentBubble()
变暗rng As范围
Set rng=ActiveDocument.Content
Do While rng.Find.Execute(“Word x”)=True
ActiveDocument.Comments.Add rng,“我第一次在气泡中输入注释”
环

设置rng=ActiveDocument.Content'谢谢Jim!工作起来很有魅力@Jim Simson,可能在这种情况下它是有效的,但我们应该尽量避免使用与特定VBA单词相同的变量名称,如
范围
,即使我们使用小写字母(范围/范围),这就是为什么必须重新定义范围的原因。我不想粗鲁无礼,只是想把这篇文章写在教育目的上。@Teamothy,谢谢你的指点。这并不粗鲁,我感谢你的反馈。我已相应地更新了我的答案。