.find添加了多条评论

时间:2012-11-07 19:42:16

标签: vba while-loop ms-word find

目的是在word文档中找到myWord的所有ocurrance并向它们添加相同的注释。我得到了两个不需要的效果:1)代码在单词的每个实例上添加了多个注释(它似乎添加了与该单词的实例数相同的共数数),以及2)代码跳过带有资本的单词字母。

Sub CheckWrd()
For Each myWord in wordArray            'wrdArray is a list of words loaded elsewhere
  With Selection.Find
   .Text = "[^13^11 ]" & wrd & "[^13^11 ,-.]"
   .Forward = True
   .Wrap = wdFindContinue
   .MatchCase = False
   .MatchWholeWord = True
  End With
  Do While Selection.Find.Execute = True
    ActiveDocument.Comments.Add Selection.range, myComment
  Loop
Next myWord

此外,如果我将Do While构造更改为和If,那么它只会添加到myWord的第一个实例。

2 个答案:

答案 0 :(得分:0)

尝试将execute循环保留在with语句中。这段代码适合我(使用大写字母有多种变体的测试文件):

Sub find_test()
    i = 1
    With ActiveDocument.Content.Find
        .Text = "test"
        .Forward = True
        .Wrap = wdFindStop
        .MatchCase = False
        .MatchWholeWord = True
        While .Execute() = True
            .Parent.Select
            ActiveDocument.Comments.Add Selection.Range, "test" & i
            i = i + 1
        Wend
    End With
End Sub

答案 1 :(得分:0)

答案:

在While中添加一个.Execute来移动东西。我不知道这是如何或为什么有效,但确实如此(它的伏都教魔法)。

(...) Do While Selection.Find.Execute = True ActiveDocument.Comments.Add Selection.range, myComment .Execute Loop

相关问题