VBA rgb to htmlRGB

What can you learn here ?
  • RGB in VBA
  • RGB for html
  • how to convert

Converting RGB color code from VBA to RGB

In Excel you can use the RGB() function to create a color made up from R(ed), G(reen) and B(lue) components. in HTML you can do the same thing but the order is different.

RGB(red,green,blue)

The RGB function in VBA returns the code that represents the mixture of red, green and blue. 

all Red
?hex(rgb(255,0,0))
FF
all Green
?hex(rgb(0,255,0))
FF00
all Blue
?hex(rgb(0,0,255))
FF0000

so rgb(red,green, blue) simply does this - which is in fact right to left bbggrr
hex(blue  * &h10000 + green * &h100 + red)

But RGB codes in html/css ( for example "style=color:#ff0000") read left to right, so we need a function to reverse them to generate an html style color code.
Public Function rgbToHTMLHex(rgbColor As Long) As String
    Dim r As Long, b As Long, g As Long
    ' extract components
    r = rgbColor Mod &H100
    g = (rgbColor \ &H100) Mod &H100
    b = (rgbColor \ &H10000) Mod &H100
    ' just swap the colors round for rgb to bgr
    rgbToHTMLHex = "#" & maskFormat(Hex(RGB(b, g, r)), "000000")

End Function
Private Function maskFormat(sIn As String, f As String) As String
    Dim s As String
    s = sIn
    If Len(s) < Len(f) Then
        s = Left(f, Len(f) - Len(s)) & s
    End If
    maskFormat = s
End Function

Comments