[Excel][VBA] セルの背景色と文字色を取得する
指定したセルに設定されている背景色や文字の色を16進形式(#000000)で取得する方法です。
アプリの設定などをEXCELブックで作ったりするのに使えます。
色の取得自体は、Interior.ColorやFont.Colorで簡単に取得できますが、16進数形式で表現するために、ひと手間かけます。
まずは関数を作成します。
'セル背景色を#000000形式の文字列で取得する
Function GetBackColor(targetCell As Range) As String
Dim Red As Long
Dim Green As Long
Dim Blue As Long
Dim targetColor As Long
Dim res As String
targetColor = targetCell.Interior.Color
Red = targetColor Mod 256
Green = Int(targetColor / 256) Mod 256
Blue = Int(targetColor / 256 / 256)
res = "#" & Right("0" & Hex(Red), 2) & _
Right("0" & Hex(Green), 2) & _
Right("0" & Hex(Blue), 2)
GetBackColor = res
End Function
'前景色(文字色)を#000000形式の文字列で取得する
Function GetFontColor(targetCell As Range) As String
Dim Red As Long
Dim Green As Long
Dim Blue As Long
Dim targetColor As Long
Dim res As String
targetColor = targetCell.Font.Color
Red = targetColor Mod 256
Green = Int(targetColor / 256) Mod 256
Blue = Int(targetColor / 256 / 256)
res = "#" & Right("0" & Hex(Red), 2) & _
Right("0" & Hex(Green), 2) & _
Right("0" & Hex(Blue), 2)
GetFontColor = res
End Function
そしてこの関数を呼び出します。
VBA内でももちろん使用できますが、シート上でも使えます。
例えば、

こんなイメージです。
簡単です。
== ランキングに参加しています。ぜひクリックお願いします ==
自作アプリが雑誌「iP!」に掲載されました [C#] DataGridViewのスクロール位置を設定する時の注意