シート内の全セルに対して、特定の色だけをクリアしたいという要望がありました。
難しそうに聞こえますが、以下サイトを参考に10分ほどで実装できました。
イメージ
Before
After
わかりにくいですが、ヘッダーの色はクリアされていないことが分かります。
実装
クリア対象の色のRGBを調べる
実装したコード
sample
Sub main()
Call clearColor(RGB(221, 235, 247))
Call clearColor(RGB(226, 239, 218))
End Sub
Function clearColor(ByVal clr As Variant)
Dim r As Range, ff As String
With ActiveSheet.UsedRange
Application.FindFormat.Interior.Color = clr
Set r = .Find("", searchformat:=True)
If Not r Is Nothing Then
ff = r.Address
Do
r.Interior.ColorIndex = 0
Set r = .Find("", after:=r, searchformat:=True)
If r Is Nothing Then Exit Do
Loop
End If
End With
End Function
ポイント
With ActiveSheet.UsedRange
Application.FindFormat.Interior.Color = clr
Set r = .Find("", searchformat:=True)
(中略)
End With
ActiveSheet.UsedRangeで使用されているセル範囲を取得します。
A1から、使用されているセルのうち一番右下のセルまでの範囲が対象となります。
Application.FindFormat.Interior.Colorでは、セル色が指定した色になっているセルを検索するように条件を設定しています。
**.Find("", searchformat:=True)**で、指定した書式となっているセルを検索しています。