2015-04-03 64 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