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