Here's an alternative method for converting between RGB → HSL in VBA, using a Windows API. Since it's a "Classic Windows" function it has a couple idiosyncrasies.
RGB to HSL with ColorRGBToHLS
ColorRGBToHLS
is an Windows API function which therefore uses an outdated color range that's been carried forward since the 1980's (originally used in a long-defunct program called MS Chart). You may be familiar with converting R/G/B values between percentages and values out of 255
.
- However in this case the conversion must be to/from values out of
240
, not 255.
- Just to further confuse us here in the future, they used notation of
HLS
instead of more-common HSL
(and hex color strings are 0xBBGGRR
instead of #RRGGBB
).
tl;dr
Option Explicit
Public Declare PtrSafe Sub ColorRGBToHLS Lib "shlwapi.dll" (ByVal clrRGB As Long, _
wHue As Integer, wLuminance As Integer, wSaturation As Integer)
Function rgb_to_hsl(r As Integer, g As Integer, b As Integer)
Dim h As Integer, s As Integer, l As Integer
ColorRGBToHLS RGB(r, g, b), h, l, s
h = 360 * (h / 239)
s = 100 * (s / 240)
l = 100 * (l / 240)
rgb_to_hsl = "hsl(" & h & "," & s & "%," & l & "%)"
End Function
...and a demo:
Sub test()
Debug.Print rgb_to_hsl(255, 180, 63) 'returns "hsl(36,100%,62%)"
End Sub
By the way the API also has a ColorHLSToRGB
function.
The 80's was a crazy (often confusing) time for computer nerds. Fun fact: Bill Gates married the first female programmer he hired.