當您想檢查評論是否已附加到文檔的某個給定部分(單詞,句子 - 範圍)時,則必須將該範圍與任何/所有現有評論。
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
感謝您的努力。但是,我對特定範圍(通常是一個單詞)的評論是多少。對整個文檔進行計數並不能解決我的問題 - 除非ActiveDocument沒有做到我認爲的那樣 - 它指的是整個文檔不是嗎? – philcolbourn 2015-04-05 07:26:17
是的,ActiveDocument確實涉及整個文檔。我誤解了你原來的問題。爲了確定您找到的文本是否有附加評論,您必須將找到的文本的範圍與文檔中的評論列表進行比較。我已經更新了上面的代碼片段來展示這一點。 – PeterT 2015-04-06 13:25:15