WebSafeColor


Description:
WebSafeColor converts a given color to the closest match in a Web Safe Color palette. It can handle normal RGB colors, as well as dealing with VB's system color constants.
 
Code:
Option Explicit

Declare Function GetSysColor Lib "user32" (ByVal nIndex As Long) As Long

Public Function WebSafeColor(ByRef nColor As OLE_COLOR) As OLE_COLOR

    If nColor < 0 Then
        ' If the color is negative, then it's one of the
        '  SystemColorConstants, so look up it's real value
        nColor = GetSysColor(nColor And &H7FFFFFFF)
    End If

    ' Call WebSafeColorSingle for each color
    '  value and add up the results
    WebSafeColor = WebSafeColorSingle(nColor And &HFF&) + _
       (WebSafeColorSingle((nColor And &HFF00&) \ &H100&) * _
       &H100&) + (WebSafeColorSingle((nColor And &HFF0000) \ _
       &H10000) * &H10000)

End Function

Public Function WebSafeColorSingle(nColor As Long) As Long

    ' The color isn't a valid color value
    Debug.Assert nColor >= 0
    Debug.Assert nColor <= 255

    ' Return the web color closest to the input color
    WebSafeColorSingle = ((nColor + 25) \ 51) * 51

End Function
 
Sample Usage:
 
    Debug.Print Hex(WebSafeColor(vbButtonFace))
    Debug.Print Hex(WebSafeColor(RGB(50, 100, 150)))