つらつら Excel VBA

私の備忘録です。

色からRGB値を算出

Sub セルの背景色をRGBで取得()
    
    'セルの背景色を取得
    Dim iColor As Long
    iColor = ActiveCell.Interior.Color
    
    '算出
    Dim iR As Long, iG As Long, iB As Long
    
    iR = iColor Mod 256
    iG = Int(iColor / 256) Mod 256
    iB = Int(iColor / 256 / 256)
    
    Debug.Print "RGB(" & iR & "," & iG & "," & iB & ")"
    
    
    '16進数に変換して算出
    Dim tempHx As String
    Dim hxRed As String, hxGreen As String, hxBlue As String
    Dim sHxRGB As String
    Dim iRed As Long, iGreen As Long, iBlue As Long
    
    tempHx = Right("00000" & Hex(iColor), 6) '#青緑赤になるので注意
    
    hxBlue = Mid(tempHx, 1, 2)
    hxGreen = Mid(tempHx, 3, 2)
    hxRed = Mid(tempHx, 5, 2)
    
    sHxRGB = "#" & hxRed & hxGreen & hxBlue '#赤緑青
    
    iBlue = CInt("&H" & hxBlue)
    iGreen = CInt("&H" & hxGreen)
    iRed = CInt("&H" & hxRed)
    
    Debug.Print "RGB(" & iRed & "," & iGreen & "," & iBlue & ")," & sHxRGB
    
End Sub

以上。