Convertir une couleur hexadécimale en valeur Color

Cette fonction permet de convertir les couleurs au format hexadécimal (par exemple : #26cfa7) en couleurs utilisables en VBA.

Notez que cette fonction accepte les couleurs au format hexadécimal avec ou sans # au début, qu'elle est compatible avec toutes les versions d'Excel et qu'elle renvoie -1 en cas d'erreur.


Pour pouvoir utiliser des couleurs au format hexadécimal en VBA, commencez par copier cette fonction dans un module :

Function hexaColor(ByVal hexa) 'Renvoie -1 en cas d'erreur

    'Conversion de couleurs hexadécimales en valeur Color - Excel-Pratique.com
    'www.excel-pratique.com/fr/astuces_vba/fonction-excel-conversion-hexa-color

    If Len(hexa) = 7 Then hexa = Mid(hexa, 2, 6) 'Si code couleur avec #
    
    If Len(hexa) = 6 Then

        tabValeurs = Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f")
        
        carac1 = LCase(Mid(hexa, 1, 1))
        carac2 = LCase(Mid(hexa, 2, 1))
        carac3 = LCase(Mid(hexa, 3, 1))
        carac4 = LCase(Mid(hexa, 4, 1))
        carac5 = LCase(Mid(hexa, 5, 1))
        carac6 = LCase(Mid(hexa, 6, 1))
        
        For i = 0 To 15
            If (carac1 = tabValeurs(i)) Then position1 = i
            If (carac2 = tabValeurs(i)) Then position2 = i
            If (carac3 = tabValeurs(i)) Then position3 = i
            If (carac4 = tabValeurs(i)) Then position4 = i
            If (carac5 = tabValeurs(i)) Then position5 = i
            If (carac6 = tabValeurs(i)) Then position6 = i
        Next
        
        If IsEmpty(position1) Or IsEmpty(position2) Or IsEmpty(position3) Or IsEmpty(position4) Or IsEmpty(position5) Or IsEmpty(position6) Then
            hexaColor = -1
        Else 
            hexaColor = RGB(position1 * 16 + position2, position3 * 16 + position4, position5 * 16 + position6)
        End If
        
    Else
        hexaColor = -1
    End If
    
End Function

Utilisez ensuite simplement la fonction hexaColor pour définir (ou récupérer) la valeur de Color.

Exemple pour colorer la cellule A1 avec la couleur #1b9426 :

Sub exemple()
    Range("A1").Interior.Color = hexaColor("#1b9426")
End Sub