フォント色を設定する
セルの文字色は Font.Color プロパティで指定します。RGB関数を使うと「赤・緑・青」を組み合わせて自由に色を作れます。初心者がつまずきやすい「色番号」「RGBの使い方」「範囲指定」を例題付きでまとめます。
基本:セルのフォント色を設定する
Sub SetFontColor_Basic()
'A1セルを赤文字に
Range("A1").Font.Color = RGB(255, 0, 0)
'B2セルを青文字に
Range("B2").Font.Color = RGB(0, 0, 255)
'C3セルを緑文字に
Range("C3").Font.Color = RGB(0, 128, 0)
End Sub
VB- ポイント:
- Font.Color に RGB(赤,緑,青) を指定。各値は 0〜255。
- 例:赤=RGB(255,0,0)、緑=RGB(0,255,0)、青=RGB(0,0,255)。
複数セル・範囲に一括で色を付ける
Sub SetFontColor_Range()
'B2:D5を濃いオレンジ文字に
Range("B2:D5").Font.Color = RGB(255, 102, 0)
End Sub
VB- ポイント: 範囲指定すれば一括で同じ文字色を設定できます。見出し行や表全体に便利。
条件に応じて文字色を変える(簡易条件付き書式)
Sub SetFontColorByCondition()
Dim last As Long, r As Long
last = Cells(Rows.Count, "E").End(xlUp).Row
For r = 3 To last
If Cells(r, "E").Value >= 1000 Then
Cells(r, "E").Font.Color = RGB(0, 112, 192) '青文字
Else
Cells(r, "E").Font.Color = RGB(192, 0, 0) '赤文字
End If
Next
End Sub
VB- ポイント: 値に応じて文字色を変えることで、簡易的な条件付き書式をVBAで実現できます。
フォント色をクリア(標準に戻す)
Sub ClearFontColor()
Range("B2:D5").Font.ColorIndex = xlColorIndexAutomatic
End Sub
VB- ポイント: ColorIndex = xlColorIndexAutomatic で標準の黒文字に戻せます。
よく使う色のテンプレート
Sub CommonFontColors()
Range("A1").Font.Color = RGB(0, 0, 0) '黒
Range("A2").Font.Color = RGB(255, 0, 0) '赤
Range("A3").Font.Color = RGB(0, 0, 255) '青
Range("A4").Font.Color = RGB(0, 128, 0) '緑
Range("A5").Font.Color = RGB(255, 165, 0) 'オレンジ
Range("A6").Font.Color = RGB(128, 0, 128) '紫
End Sub
VB例題で練習
例題1:見出し行を青文字+太字に
Sub Example_HeaderFormat()
With Range("B2:E2")
.Font.Color = RGB(0, 0, 255)
.Font.Bold = True
.HorizontalAlignment = xlCenter
End With
End Sub
VB例題2:金額列で1,000以上は青文字、未満は赤文字
Sub Example_AmountHighlight()
Dim last As Long, r As Long
last = Cells(Rows.Count, "E").End(xlUp).Row
For r = 3 To last
If Cells(r, "E").Value >= 1000 Then
Cells(r, "E").Font.Color = RGB(0, 112, 192)
Else
Cells(r, "E").Font.Color = RGB(192, 0, 0)
End If
Next
End Sub
VB例題3:交互に文字色を変えて見やすくする
Sub Example_AlternateRowFontColors()
Dim last As Long, r As Long
last = Cells(Rows.Count, "B").End(xlUp).Row
For r = 3 To last
If r Mod 2 = 0 Then
Rows(r).Font.Color = RGB(0, 0, 255) '青文字
Else
Rows(r).Font.Color = RGB(0, 0, 0) '黒文字
End If
Next
End Sub
VB実務の落とし穴と対策
- ColorとColorIndexの混同: ColorはRGB指定、ColorIndexはExcel標準パレット番号。RGBの方が自由度が高い。
- 大量範囲で遅い: ScreenUpdating=False を併用し、必要範囲だけに色を付ける。
- 条件付き書式との競合: VBAで色を付けると条件付き書式が上書きされる。条件付き書式を使う方が管理しやすい場合もある。
- 印刷で見えにくい: 薄い色は印刷時に見えないことがある。提出用は濃いめの色を選ぶ。
