Regex 使用正则表达式和注释的Word VBA
我使用带有VBA宏的正则表达式在word文件中查找匹配项,因为在某些情况下,查找函数是不够的。 应标记匹配项(有效),并应用注释。 但是,如果我添加注释(或注释已经存在),则Match.FirstIndex会因之前的每一条注释而被抛出。 与同一文本的注释计数为1 为什么呢?如何修复它 简化示例:Regex 使用正则表达式和注释的Word VBA,regex,vba,ms-word,Regex,Vba,Ms Word,我使用带有VBA宏的正则表达式在word文件中查找匹配项,因为在某些情况下,查找函数是不够的。 应标记匹配项(有效),并应用注释。 但是,如果我添加注释(或注释已经存在),则Match.FirstIndex会因之前的每一条注释而被抛出。 与同一文本的注释计数为1 为什么呢?如何修复它 简化示例: Sub Mark_QuestionAndExpressionMarks() Dim Match As Match Dim Matches Dim regEx As New reg
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
在正则表达式中并不深刻,所以我尝试了一种不同的方法来解决这个问题。希望能有帮助
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
是word还是Excel?如果两者都是,那么每一个都是如何涉及的?只有单词,没有Excel。因此,问题是突出显示设置在
?
或之前的字符上代码>与第二个和以下匹配,对吗?这真的很奇怪,因为match FirstIndex计算正确。在匹配之前,文本中的每个注释集的索引都是一个。在出现注释之前,文本的任何部分上是否有注释?或对于每个“唯一”评论,索引将少一个。我希望它仍然会突出并评论以下所有问题或表达标记,即使对文本的某些部分有评论。