Colour Code Conversions

TimTDP

Registered User.
Local time
Today, 19:52
Joined
Oct 24, 2008
Messages
213
If a colour is stored in Hex format, how can I use VBA to get the RGB equivalent or the font colour number

eg #9999FF = RGB(153, 153, 255) = Color 17


Thanks in advance
 
Code:
Sub TestIt()

    MsgBox Hex2RGB("#99 99 FF") & "  " & RGB(153, 153, 255)

End Sub

Public Function Hex2RGB(ByVal strHexIn As String) As Long
    Dim intX     As Integer
    Dim intTemp  As Integer
    Dim lngPower As Long
    Dim lngTotal As Long

    strHexIn = UCase(strHexIn)
    strHexIn = Replace(strHexIn, " ", "")
    strHexIn = Replace(strHexIn, "#", "")
    lngPower = 1
    
    For intX = 1 To Len(strHexIn)
        intTemp = Asc(Mid(strHexIn, intX, 1))
        If intTemp < 58 Then
            intTemp = intTemp - 48
        Else
            intTemp = intTemp - 55
        End If
        
        lngTotal = lngTotal + intTemp * lngPower
        lngPower = lngPower * 16
    Next intX
    
    Hex2RGB = lngTotal

End Function
 
Sorry, I should have also asked:

If the colour is stored as a long integer, how can I use VBA to get the RGB equivalent or the font colour number

eg 65280 = RGB(??, ??, ???)

or 65280 = HexNumber and then I can use ChrisO's code to conver to RGB
 
Code:
Public Type udtL2RGB
    Red   As Long
    Green As Long
    Blue  As Long
End Type


Sub TestLongToRGB()
    Dim lngColour As Long
    
    lngColour = 65280
    
    With LongToRGB(lngColour)
        MsgBox lngColour & "  =  " & _
               .Red & ", " & .Green & ", " & .Blue & "  =  " & _
               RGB(.Red, .Green, .Blue)
    End With

End Sub


Public Function LongToRGB(ByVal lngColor As Long) As udtL2RGB

    LongToRGB.Red = lngColor And 255
    LongToRGB.Green = (lngColor And 65280) \ 256
    LongToRGB.Blue = (lngColor And 16711680) \ 65536

End Function
 

Users who are viewing this thread

Back
Top Bottom