2015-04-03 67 views
1

在Word文档中使用range.Find对象我遍历所有匹配并添加注释。in VBA(word)只有在没有评论的情况下,我如何才能将评论添加到范围内?

但是,如果评论已经存在,我不想添加其他评论 - 所以我可以在同一文档上多次运行VBA脚本。

这里是我的循环:

Dim all As Range 
Set all = pcSetupFind(word, wdFindStop) ' setup all.find to find 'word' 
While all.Find.Execute 
    If all.Find.Found Then 
    If all.Comments.Count = 0 Then Call all.Comments.Add(all, comment) 
    End If 
Wend 

但是,它总是添加注释。

如何仅在没有评论时添加评论范围?

回答

3

当您想检查评论是否已附加到文档的某个给定部分(单词,句子 - 范围)时,则必须将该范围与任何/所有现有评论。

Option Explicit 

Function CommentExistsInRange(checkRange As Range) As Boolean 
    '--- compares all existing comments to the given range and 
    ' checks for a match. 
    ' RETURNS true if a comment exists for the given range 
    Dim commentScope As Range 
    Dim i As Integer 
    Dim totalComments As Integer 
    totalComments = ActiveDocument.Comments.Count 
    CommentExistsInRange = False 
    If totalComments > 0 Then 
     For i = 1 To totalComments 
      Set commentScope = ActiveDocument.Comments.Item(i).Scope 
      If (checkRange.Start = commentScope.Start) And _ 
       (checkRange.End = commentScope.End) Then 
       CommentExistsInRange = True 
       Exit Function 
      End If 
     Next i 
    End If 
End Function 

Sub FindAndComment(findText As String, searchRange As Range, newComment As String) 
    Dim foundTextRange As Range 
    With searchRange 
     .Find.Text = findText 
     .Find.Wrap = wdFindStop 
     .Find.Forward = True 
     While .Find.Execute 
      If .Find.Found Then 
       .Select 
       Set foundTextRange = ActiveDocument.Range(Selection.Range.Start, _ 
                  Selection.Range.End) 
       If Not CommentExistsInRange(foundTextRange) Then 
        Call ActiveDocument.Comments.Add(foundTextRange, newComment) 
       End If 
      End If 
     Wend 
    End With 
End Sub 

Sub Test() 
    FindAndComment "Office", ActiveDocument.Range, "Around the Office watercooler" 
End Sub 
+0

感谢您的努力。但是,我对特定范围(通常是一个单词)的评论是多少。对整个文档进行计数并不能解决我的问题 - 除非ActiveDocument没有做到我认为的那样 - 它指的是整个文档不是吗? – philcolbourn 2015-04-05 07:26:17

+0

是的,ActiveDocument确实涉及整个文档。我误解了你原来的问题。为了确定您找到的文本是否有附加评论,您必须将找到的文本的范围与文档中的评论列表进行比较。我已经更新了上面的代码片段来展示这一点。 – PeterT 2015-04-06 13:25:15

0

我拿走了PeterT的方法,并以不同的方式实现它。

Function pcHasComments(rng As Range) As Boolean 

    Dim com As comment 

    For Each com In ActiveDocument.comments 
    If com.scope.Start = rng.Start And com.scope.End = rng.End Then 
     'MsgBox ("found comment") 
     pcHasComments = True 
     Exit Function 
    End If 
    Next 

    pcHasComments = False 

End Function 
+0

感谢@philcolbourn,效率更高,更简单! – PeterT 2015-04-08 18:51:58

+0

@彼得特:不客气。尽管我需要你的想法。我猜如果我想在这个范围内评论,那么我需要一个更复杂的条件。 – philcolbourn 2015-04-09 02:32:23