I\'m trying to set a public const of a color in my VBA code. Normally, I can use:
Dim BLUE As Long
BLUE = RGB(183, 222, 232)
However, ther
The reason for the apparent reversal is that the RGB() function actually creates a BGR value.
More specifically, the red byte is the low order byte and the blue byte is the high order byte (or third of four at least).
Try this example in the Immediate window:
x = RGB(255, 0, 128) ' full red, half blue
? hex(x)
8000FF
x = RGB(128, 0, 255) ' half red, full blue
? hex(x)
FF0080
Note that the "full" byte (255 or FF) and the "half-full" byte (128 or 80) end up on the opposite sides in each result. That's why you need to specify the hex constant in the reverse order from what you'd expect to get the same value.
Also, no need to use an online converter. The Hex() function provides the hex value of the number given to it, and Int will take a string in hex format and return the decimal value:
? Int("&hff0000")
16711680
Update:
So to use this information to create your hex constants, you just run your RGB() and Hex() statements in the Immediate window as above (type Ctrl+G to open and close it), then use the resulting Hex value as your constant. If the value is less than 6 digits long, you can pad it on the left with zeros, but that's technically not necessary:
x = RGB(183, 222, 232)
? "Public Const MyBlue = &h" & hex(x)
Public Const MyBlue = &hE8DEB7
then copy that last line into your code.
OK, the following will take the color of a cell in Excel 2010 and provide a valid Hexcode:
Public Function getHexCol(a As Range)
' In excel type in for example getHexCol(A1) to get the hexcode of the color on A1.
Dim strColour As String
Dim hexColour As String
Dim nColour As Long
Dim nR As Long, nB As Long, nG As Long
strColour = a.Interior.Color
If Len(strColour) = 0 Then Exit Function
nColour = Val(strColour) ' convert string to decimal number
hexColour = Hex(nColour) ' convert decimal number to hex string
While Len(hexColour) < 6 ' pad on left to 6 hex digits
hexColour = "0" & hexColour
Wend
nB = CLng("&H" & Mid(hexColour, 1, 2))
nG = CLng("&H" & Mid(hexColour, 3, 2))
nR = CLng("&H" & Mid(hexColour, 5, 2))
getHexCol = Hex(RGB(nB, nG, nR))
End Function
Function GetRGB(ByVal cell As Range) As String
Dim R As String, G As String
Dim b As String, hexColor As String
hexCode = Hex(cell.Interior.Color)
'Note the order excel uses for hex is BGR.
b = Val("&H" & Mid(hexCode, 1, 2))
G = Val("&H" & Mid(hexCode, 3, 2))
R = Val("&H" & Mid(hexCode, 5, 2))
GetRGB = R & ":" & G & ":" & b
End Function
note that excel RGB values are backwards (BGR)
You'll have to reverse the bytes into order
BLUE = &HE8DEB7
to get the correct color value.
I tested this code, cant realy follow Howard's answer
Dim rd, gr, bl As Integer
rd = 183
gr = 222
bl = 232
BLUE = RGB(rd, gr, bl)
hexclr = Format(CStr(Hex(rd)), "00") +
Format(CStr(Hex(gr)), "00") +
Format(CStr(Hex(bl)), "00")
MsgBox hexclr 'B7DEE8