VBA Change Excel cell part text by regex


Sub CellPartTextColorChange()

'ColorIndex=41(青色)
Dim strColorIndex As Integer: strColorIndex = 41

Dim RE As Object, REMatches As Object
Set RE = CreateObject("vbscript.regexp")

  With RE
        .MultiLine = False  '文字列の複数行設定
        .Global = True '文字列全体検索設定
        .IgnoreCase = False '大文字小文字区別検索設定
     
        '[]{}内の文字列を検索
        .pattern = "\[(.*?)\]+|\{(.*?)\}+"
  End With

'色変換する文字列の開始Position
Dim startPos As Integer: startPos = 1

Dim matchPos As Integer: matchPos = 0

'置き換えをしたい文字列
Dim trgText As String: trgText = ActiveCell.Value

Set REMatches = RE.Execute(trgText)

For Each SearchChar In REMatches
'---- 検索する文字列の長さ
Dim SearchCharLen As Integer: SearchCharLen = Len(SearchChar)
'-------------------------------

'ここで文字列を比較してビットする文字列の開始Position取得
matchPos = InStr(startPos, trgText, SearchChar, vbTextCompare)

'文字列の部分テキスト青色に変換する
ActiveCell.Characters(Start:=matchPos, Length:=SearchCharLen).Font.ColorIndex = strColorIndex
'
'比較する文字列の開始Position変更(変更しないと同じ検索テキスト複数ある場合はじめのテキストのみ色変換される)
startPos = matchPos + SearchCharLen
                 
Next SearchChar

End Sub
--------------------------------------------------------------------------------
結果:
[X.X] km [XXXX] km [X.X] mi [{XXXX}] mi