【问题标题】:Word VBA: finding a set of words and inserting predefined commentsWord VBA:查找一组单词并插入预定义的注释
【发布时间】:2019-10-23 23:23:59
【问题描述】:

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

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

  • Wordset 1:每个找到的词都有相同的评论
  • Wordset 2:单个 cmets(我建议根据已识别的单词创建新文本)

我一直在用一个代码半自动化这个过程,该代码识别所有识别的单词并突出显示它们,帮助我完成整个过程(但我仍然需要手动输入所有 cmets - 而且我也能够输入 cmets -但一次只能说一个词。)由于我的 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

我试图通过如下所示的方式重复该过程,但出于我确信你们中的许多人都清楚(而且我完全不知道)的原因 - 这个策略失败了,适用于“单词 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

我已经混合和匹配了这些代码,但无济于事。有什么想法可以帮助我处理这两个词集吗?

感谢大家的帮助!

最好的问候

【问题讨论】:

    标签: vba ms-word


    【解决方案1】:

    Benoit,你快到了!您需要做的就是在第一次循环之后重新定义范围对象(因为那时它已经用尽了)。像这样:

    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
    

    这应该对你有用(它对我有用)。如果没有,请告诉我。

    【讨论】:

    • 谢谢吉姆!像魅力一样工作!
    • @Jim Simson ,可能在这种情况下它可以工作,但我们应该尽量避免使用与特定 VBA 单词相同的变量名称,例如 range,即使我们使用小写字母(范围/ Range),这就是为什么你必须重新定义范围。我不想粗鲁,只是想出于教育目的写这篇文章。
    • @Teamothy,感谢您的指点。这并不粗鲁,我感谢您的反馈。我已经相应地更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-06
    • 2014-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多