我正在使用带有VBA宏的RegEx来查找word文件中的匹配项,因为在某些情况下查找功能不够用。 应该标记匹配(工作)并且应该评论评论。 但是,如果我添加注释(或注释已经存在),Match.FirstIndex会因为每个先前的注释而被抛出一个。 具有相同文本的评论为一个。
为什么?如何解决?
简化示例:
Sub Mark_QuestionAndExpressionMarks()
Dim Match As Match
Dim Matches
Dim regEx As New regExp
regEx.Pattern = "\?|!" 'regex for questionmark or expressionmark
regEx.IgnoreCase = False
regEx.Global = True
Set Matches = regEx.Execute(ActiveDocument.Content.Text) ' or ActiveDocument.Content.Text
For Each Match In Matches
Call HighlightAndComment(ActiveDocument.range(Match.FirstIndex, Match.FirstIndex + Len(Match.Value)), "Question or Expressionmark")
// problem here as Match is realized correctly but the FirstIndex is off
Next
End Sub
Sub HighlightAndComment(WordOrSentence As Object, comment As String)
WordOrSentence.HighlightColorIndex = wdYellow
Call ActiveDocument.range.Comments.Add(WordOrSentence, comment)
End Sub
答案 0 :(得分:0)
正则表达式并不深刻所以我尝试了一种不同的方法来解决这个问题。希望它有所帮助。
Sub Mark_QuestionAndExpressionMarks()
Dim charsToSearch As String
charsToSearch = "?!"
Dim doc As Document
Set doc = ActiveDocument
Dim j As Integer
For j = 1 To doc.Range.characters.Count
'Check if character is one of the searched ones
If (InStr(charsToSearch, doc.Range.characters(j)) > 0) Then
Call HighlightAndComment(doc.Range.characters(j), "Question or Expressionmark")
End If
Next
End Sub