I'd like to expand on Tim Williams terrific answer. I needed to be able to show a hex value in my cells based on other cells. I also want the font set to either white or black because of this. So I modified the function as follows:
Function hexColor(r, g, b)
Dim bclr As Long, fclr As Long, src As Range, sht As String, f, v
If IsEmpty(r) Or IsEmpty(g) Or IsEmpty(b) Then
bclr = vbWhite
fclr = vbBlack
Else
bclr = RGB(r, g, b)
If ((r * 0.299) + (g * 0.587) + (b * 0.114) > 186) Then
fclr = vbBlack
Else
fclr = vbWhite
End If
End If
Set src = Application.ThisCell
sht = src.Parent.Name
f = "Changeit(""" & sht & """,""" & _
src.Address(False, False) & """," & bclr & "," & fclr & ")"
src.Parent.Evaluate f
Dim hr As String, hg As String, hb As String
hr = Right("0" & Hex(r), 2)
hg = Right("0" & Hex(g), 2)
hb = Right("0" & Hex(b), 2)
hexColor = "#" & hr & hg & hb
End Function
Sub ChangeIt(sht, c, bclr As Long, fclr As Long)
ThisWorkbook.Sheets(sht).Range(c).Interior.Color = bclr
ThisWorkbook.Sheets(sht).Range(c).Font.Color = fclr
End Sub
This means I can enter the following two cell values: =hexColor(185,201,225)
and
=hexColor(115,146,198)
and get the following result:
SomeCell.Interior.Color = RGB(150, 220, 90)
– Dyarchy