Converting VBA Long Color Values to RGB

Color values in VBA are stored as Long integers.  

To get the long integer value of a color from its primary color components, you can use the RGB function.  But what if you want to go in the other direction?  Don't worry, I've got a function for that.

Calculating the Long Color Values

As I noted above, you can use the built-in RGB() function to calculate the long integer color values.  However, the math to create those values by hand is straightforward:

Red × 256⁰ + Green × 256¹ + Blue × 256²

For example, the color gray (RGB(128, 128, 128) = 8421504) is calculated as follows:

Red × 256⁰ + Green × 256¹ + Blue × 256²
128 × 256⁰ +   128 × 256¹ +  128 × 256²
128 × 1    +   128 × 256  +  128 × 65,536
   128     +     32,768   +    8,388,608
                8,421,504

Test Driven Development

Before we write the function, we'll write some tests to cover the various cases.  I can't use the color constants in my tests (such as vbYellow), so I use the literal values instead.

To run these tests, you'll need my DocTests function (or Ben Clothier's recently released tUnitVba add-in; source code only for now).

'Black
'>>> ConvertColorToRgb(0)
'RGB(0, 0, 0)

'Red/Dark Red
'>>> ConvertColorToRgb(255)
'RGB(255, 0, 0)
'>>> ConvertColorToRgb(128)
'RGB(128, 0, 0)

'Green/Dark Green
'>>> ConvertColorToRgb(65280)
'RGB(0, 255, 0)
'>>> ConvertColorToRgb(RGB(0, 128, 0))
'RGB(0, 128, 0)

'Blue/Dark Blue
'>>> ConvertColorToRgb(16711680)
'RGB(0, 0, 255)
'>>> ConvertColorToRgb(RGB(0, 0, 128))
'RGB(0, 0, 128)

'Yellow/Dark Yellow
'>>> ConvertColorToRgb(65535)
'RGB(255, 255, 0)
'>>> ConvertColorToRgb(RGB(128, 128, 128))
'RGB(128, 128, 128)

'White
'>>> ConvertColorToRgb(16777215)
'RGB(255, 255, 255)

Once I had created the above tests, I began building the function to satisfy them.  And once all the tests passed, I was done:

The Code: ConvertColorToRgb

' ----------------------------------------------------------------
' Procedure : ConvertColorToRgb
' Date      : 12/29/2022
' Author    : Mike Wolfe
' Source    : https://nolongerset.com/convertcolortorgb/
' Purpose   : Converts a Long color value to the equivalent
'               RGB function call.
' ----------------------------------------------------------------
Function ConvertColorToRgb(ColorValue As Long) As String
    Dim Red As Long, Green As Long, Blue As Long    
    Red = ColorValue Mod 256
    Green = ((ColorValue - Red) / 256) Mod 256
    Blue = ((ColorValue - Red - (Green * 256)) / 256 / 256) Mod 256
    
    ConvertColorToRgb = "RGB(" & _
                    Red & ", " & _
                    Green & ", " & _
                    Blue & ")"
End Function

External references

RGB function (Visual Basic for Applications)
Office VBA reference topic