What can you learn here?

  • RGB VBA
  • RGB for html
  • How to convert

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

Summary

For more tips like this, take a look at Get Started Snippets In the meantime why not join our forum, follow the blog or follow me on twitter to ensure you get updates when they are available. You can also submit anything you want considered for publication on this site to our forum.

See A tagCloud in Outlook for an example of this function.