インストールレスプログラミング( ´ー`)

VBA , JavaScript , HTAなど 365アプリはインストール必要ですが、仕事に無いケースはほぼないから(・_・;)

Word VBA 正規表現を使う。 VBScript_RegExp

正規表現の本を頭を抱えながら,読んでいます。

ピンと来ないことも多く,VBAでテストできる環境を作るためのコードをとりあえず作りながら読んでいます。

Word VBAです。
Microsoft VBScript Regular Expressions 5.5への参照設定が必要です。

Sub a()
    Dim Regex As VBScript_RegExp_55.Regexp
    Set Regex = New VBScript_RegExp_55.Regexp
    
    Dim Sentence As Range
    Dim ret As VBScript_RegExp_55.MatchCollection
    Dim MatchSentence As Match
    Dim retCol As Collection: Set retCol = New Collection
    
    Regex.Pattern = "^A.*d$"
    Regex.Global = True
    Regex.IgnoreCase = False
    Regex.MultiLine = True
    
    For Each Sentence In ActiveDocument.Sentences
        Set ret = Regex.Execute(Sentence)
        If Regex.Test(Sentence.Text) Then
            Sentence.Font.ColorIndex = wdRed
            For Each MatchSentence In ret
                retCol.Add Replace(Sentence.Text, vbCr, "[vbCr]") & vbTab & Sentence.Start & " " & Sentence.End
            Next
        Else
            Sentence.Font.ColorIndex = wdBlack
        End If
    Next

    Dim w As Variant
    Dim i As Long: i = 1
    For Each w In retCol
        Debug.Print i; " " & w
        i = i + 1
    Next
End Sub

難しいですね。単語単位では正規表現が活きないと思うので,Sentence区切りです。

For eachを使おうとしても,Wordコレクションに対してWord,Sentencesコレクションに対してSentenceオブジェクトはありません。どちらもRangeオブジェクトになる。

Wordの作法でも引っかかり,なかなか興味深い練習になっています。
f:id:chemiphys:20170226111351p:plain

    Regex.Pattern = "^A.*d$"

この部分に正規表現を入れてチェックします。
コードを見ていただければわかりますが,正規表現にマッチした段落の文字が赤になる感じです。

出かけないといけないので,とりあえずここまで。
がんばらないといけません。