VBA: not the right color

Viewed 249

I'd like to use a cell's background color in an HTML file. Thus, I need the HEX code of the color. I use the following code to get the HEX code of the background color.

MsgBox (ActiveCell.Interior.Color)
MsgBox Right("000000" & Hex(ActiveCell.Interior.Color), 6)

The fist line returned 2303331, the second 232563. I tried on two different web sites to convert 2303331 to HEX number. Both gave #232563. I also tried the reverse conversion, converting #232563 to decimal, and got 2303331. So, the numbers are OK.

I then entered #232563 on two different web sites to see if the color matches that on my Excel sheet. No, it doesn't match. #232563 is a blue color while my color is brown, similar to #450000.

I'm lost as to how to get the HEX code of the cell background.

enter image description here

3 Answers

If you try this: hex( RGB(30, 30, 50)) You will see the answer is 321E1E ==> VBA stores the RGB as.... BGR.

Try the color #632523 ;-)

You must reverse the Hex obtained string:

Sub testHexColor()
 Dim hexStringCol As String
  MsgBox (ActiveCell.Interior.Color)
  hexStringCol = Right("000000" & Hex(ActiveCell.Interior.Color), 6)
  Debug.Print hexStringCol
  hexStringCol = "#" & Right(hexStringCol, 2) & Mid(hexStringCol, 3, 2) & left(hexStringCol, 2)
  Debug.Print hexStringCol 'this is the correct one
End Sub

You can test it extracting the RGB from the obtained Hex string and color the neighbor cell:

ActiveCell.Offset(0, 1).Interior.Color = HEXCOL2RGB(hexStringCol)

And use the next conversion function:

Private Function HEXCOL2RGB(ByVal HexColor As String) As String
 Dim Red As String, Green As String, Blue As String
 HexColor = Replace(HexColor, "#", "")
  Red = val("&H" & Mid(HexColor, 1, 2))
  Green = val("&H" & Mid(HexColor, 3, 2))
  Blue = val("&H" & Mid(HexColor, 5, 2))
  HEXCOL2RGB = RGB(Red, Green, Blue)
End Function

For future reference, you could use this small, free, utility program which will give the colors you require in, pretty much, any format you want: RGB, VB HEX, Delphi HEX, HTML HEX etc.

http://colorcop.net/

Related