2016-07-13 5 views
-2

VBAマクロでRegExを使用して、検索機能が不十分な場合があるため、ワードファイル内で一致するものを見つけることができます。 マッチはマークされていなければなりません(作業中)、コメントを適用する必要があります。 しかし、コメント(またはコメントが既に存在する)を追加した場合、Match.FirstIndexは前回のコメントごとに1つずつスローされます。 同じテキストが1つと数えるコメント。RegExとコメントを使用したWord VBA

なぜですか?それを修正するには?

簡単な例:

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

単語またはExcelですか?それが両方の場合、どのように関係していますか? – Deduplicator

+0

Wordのみ、いいえexcel – Nandmp

+0

ハイライトは '?'や '!'の前に2番目以降の文字でハイライトが設定されているのですか?一致FirstIndexが正しく計算されるので、これは本当に奇妙です。 –

答えて

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 
関連する問題