将十进制或 RGB 颜色代码转换为 HTML(十六进制)代码

Convert Decimal or RGB color code to HTML (Hex) code

如何使用 VBA 或Excel 工作表?

示例:

INPUT:         OUTPUT:
123456         #40E201
vbRed          #FF0000
(48, 151, 62)  #30973E

以下 VBA 函数将 十进制颜色代码 016777215)转换为十六进制 HTML 颜色代码(#000000#FFFFFF):

Function Dec2HexColor(decColor As Long) As String
    If decColor > 16777215 Then decColor = 16777215
    If decColor < 0 Then decColor = 0
    Dec2HexColor = "#" & Right("00" & Hex((decColor Mod 256)), 2) & _
                         Right("00" & Hex((decColor \ 256) Mod 256), 2) & _
                         Right("00" & Hex(decColor \ 65536), 2)
End Function

它也可以与一组 RGB 颜色值(红色、绿色、蓝色;每个 0255)组合使用它与 VBA 的 RGB 函数一起使用,如下所示。

示例:

Sub test()
    Debug.Print Dec2HexColor(vbRed)              'returns: "#FF0000"
    Debug.Print Dec2HexColor(vbGreen)            'returns: "#00FF00"
    Debug.Print Dec2HexColor(vbMagenta)          'returns: "#FF00FF"
    Debug.Print Dec2HexColor(12345678)           'returns: "#4E61BC"
    Debug.Print Dec2HexColor(0)                  'returns: "#000000"
    Debug.Print Dec2HexColor(RGB(255, 0, 0))     'returns: "#FF0000"
    Debug.Print Dec2HexColor(RGB(48, 151, 62))   'returns: "#30973E"
End Sub