0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Excelでセル内の特定文字テキストだけ色を付けるマクロ

0
Posted at
VBA
Sub 正規表現で赤くする()

    Dim c As Range
    Dim reg As Object
    Dim matches As Object
    Dim m As Object

    Set reg = CreateObject("VBScript.RegExp")

    '対象パターン
    reg.Pattern = "(new|stay|update)\(-?\d+(\.\d+)?\)"
    reg.Global = True
    reg.IgnoreCase = True

    For Each c In Selection

        If Not IsError(c.Value) Then

            Set matches = reg.Execute(CStr(c.Value))

            For Each m In matches

                c.Characters( _
                    Start:=m.FirstIndex + 1, _
                    Length:=m.Length _
                ).Font.Color = vbRed

            Next m

        End If

    Next c

End Sub

今回の正規表現
(new|update)(-?\d+(.\d+)?)

を分解すると、意外と単純です。

部分 意味 マッチ例
(new|stay|update) new / stay / update のどれか new
\( ( そのもの (
-? - が「あってもなくてもよい」 -
\d+ 数字が1文字以上 2、26
(\.\d+)? 小数部分が「あってもなくてもよい」 .6
\) ) そのもの )

特に覚えておくと便利な記号
今回なら、まずこの5つを覚えるだけでかなり使えます。

  • | → または。new|stay なら new または stay
  • ? → 直前のものが0回または1回。-? ならマイナスがあってもなくてもOK
    • → 直前のものが1回以上。\d+ なら数字が1桁以上
  • \d → 数字1文字
  • \ → 記号を文字そのものとして扱う。. は正規表現では特別な意味があるので、普通の「.」を探すなら .
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?