セルの背景色を設定する
セルの背景色は Interior.Color プロパティで指定します。RGB関数を使うと「赤・緑・青」を組み合わせて自由に色を作れます。初心者がつまずきやすい「色番号」「RGBの使い方」「範囲指定」を例題付きでまとめます。
基本:セルの背景色を設定する
Sub SetCellBackground_Basic()
'A1セルを黄色に
Range("A1").Interior.Color = RGB(255, 255, 0)
'B2セルを水色に
Range("B2").Interior.Color = RGB(0, 255, 255)
'C3セルを灰色に
Range("C3").Interior.Color = RGB(200, 200, 200)
End Sub
VB- ポイント:
- Interior.Color に RGB(赤,緑,青) を指定。各値は 0〜255。
- 例:赤=RGB(255,0,0)、緑=RGB(0,255,0)、青=RGB(0,0,255)。
複数セル・範囲に一括で色を付ける
Sub SetRangeBackground()
'B2:D5を薄いオレンジに
Range("B2:D5").Interior.Color = RGB(255, 230, 153)
End Sub
VB- ポイント: 範囲指定すれば一括で同じ色を設定できます。見出し行や表全体に便利。
条件に応じて色を変える(簡易条件付き書式)
Sub SetBackgroundByCondition()
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").Interior.Color = RGB(198, 239, 206) '緑系
Else
Cells(r, "E").Interior.Color = RGB(255, 199, 206) '赤系
End If
Next
End Sub
VB- ポイント: 値に応じて背景色を変えることで、簡易的な条件付き書式をVBAで実現できます。
背景色をクリア(元に戻す)
Sub ClearBackground()
Range("B2:D5").Interior.ColorIndex = xlColorIndexNone
End Sub
VB- ポイント: ColorIndex = xlColorIndexNone で背景色を解除できます。
よく使う色のテンプレート
Sub CommonColors()
Range("A1").Interior.Color = RGB(255, 255, 255) '白
Range("A2").Interior.Color = RGB(0, 0, 0) '黒
Range("A3").Interior.Color = RGB(255, 0, 0) '赤
Range("A4").Interior.Color = RGB(0, 255, 0) '緑
Range("A5").Interior.Color = RGB(0, 0, 255) '青
Range("A6").Interior.Color = RGB(255, 255, 0) '黄
End Sub
VB例題で練習
例題1:見出し行をグレーにして太字に
Sub Example_HeaderFormat()
With Range("B2:E2")
.Interior.Color = RGB(217, 217, 217)
.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").Interior.Color = RGB(198, 239, 206)
Else
Cells(r, "E").Interior.Color = RGB(255, 199, 206)
End If
Next
End Sub
VB例題3:交互に背景色を付けて見やすくする
Sub Example_AlternateRowColors()
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).Interior.Color = RGB(242, 242, 242) '薄グレー
Else
Rows(r).Interior.ColorIndex = xlColorIndexNone '色なし
End If
Next
End Sub
VB実務の落とし穴と対策
- 色番号の混乱: ColorIndex と Color は別物。ColorIndex はExcel標準パレット番号、ColorはRGB指定。RGBの方が自由度が高い。
- 大量範囲で遅い: ScreenUpdating=False を併用し、必要範囲だけに色を付ける。
- 条件付き書式との競合: VBAで色を付けると条件付き書式が上書きされる。条件付き書式を使う方が管理しやすい場合もある。
- 印刷で見えにくい: 薄い色を選ぶと印刷時に見えないことがある。提出用は濃いめの色を選ぶ。
