セル内の特定の文字のみを色付・太字に一括変更するVBA

〇このコードでできること

選択したセルの中にある特定の文字(例えば「重要」など)のみを「太字・赤字・黄色塗りつぶし」にしたりできます。

作成イメージ。

〇コード・使い方

  • 以下コードをコピー、VBEに貼り付け
Sub Main()
Const 赤色文字 As Byte = 3
Const 青色文字 As Byte = 5
Const 黄色文字 As Byte = 6
Const 赤色塗潰 As Byte = 3
Const 青色塗潰 As Byte = 5
Const 黄色塗潰 As Byte = 6
Const 無色塗潰 As Byte = 0
Const 太字にする As Boolean = True
Const 太字にしない As Boolean = False
Call HighlightTexts("目立たせたい文字を入力", Selection, 赤色文字, 太字にする, 無色塗潰)
End Sub
Sub HighlightTexts _
(targetString As String, _
 selectedCells As Range, _
 Optional charColor As Byte = 3, Optional charBold As Boolean = True, Optional cellColor As Byte = 0)
    Dim cell As Range
    Dim startStr As Integer
    Dim textLength As Integer
    textLength = Len(targetString)
    For Each cell In selectedCells
        startStr = InStr(cell.Value, targetString)
        If startStr <> 0 Then
            cell.Interior.ColorIndex = cellColor
        End If
        Do While startStr > 0
            With cell.Characters(Start:=startStr, Length:=textLength).Font
                .ColorIndex = charColor
                .Bold = charBold
                
            End With
            startStr = InStr(startStr + 1, cell.Value, targetString)
        Loop
    Next cell
End Sub
  • HighlightTexts("目立たせたい文字を入力", Selection, 赤色文字, 太字にする, 無色塗潰)
    の下線部分を適宜修正。
  • Excelシート上の対象のシートを選択
  • Sub Mainを実行。色付けされる。
  • (補足)赤色の他、青や黄色の文字色、塗りつぶしにすることも可能。例えば「青色文字の黄色塗りつぶし」にしたければ、以下のように記述する。指定できる色は「Const」と書かれているカレーパレットから指定。
HighlightTexts("目立たせたい文字を入力", Selection, 青色文字, 太字にする, 黄色塗潰)

〇【動画】コード解説、使い方

動画でも使い方を確認できます、詳しいコードの解説もこちらから。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です