プロプログラマ

プログラマーを職業としてます。 Flex,Air,C#,Oracle,HTML+JSの言語ノウハウを中心に情報発信していきます

[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内でももちろん使用できますが、シート上でも使えます。
例えば、
WS000000

こんなイメージです。
簡単です。

 

== ランキングに参加しています。ぜひクリックお願いします ==

プログラム ブログランキングへ
にほんブログ村 IT技術ブログへ
にほんブログ村

コメントを残す

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

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください