How do I create a function that creates a color square like in the picture below?

70 views Asked by At

How do I create a function that creates a color square like in the picture below?

So, I need to create a function that generates a color square as below:

enter image description here

I tried to do that...

Sub GenererCarreCouleur()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets(1) ' Changez le numéro de feuille si nécessaire
    
    Dim rng As Range
    Set rng = ws.Range("A1:G8")
    
    Dim i As Integer, j As Integer, count As Integer
    count = 1
    
    For i = 1 To 8
        For j = 1 To 7
            rng.Cells(i, j).Value = count
            rng.Cells(i, j).Interior.Color = GetCouleur(count)
            count = count + 1
        Next j
    Next i
End Sub

Function GetCouleur(ByVal valeur As Integer) As Long
    ' Ajoutez autant de cas que nécessaire pour couvrir toutes les valeurs jusqu'à 56
    Select Case valeur
        Case 1 To 7
            GetCouleur = RGB(0, 0, 0) ' Noir
        Case 8 To 14
            GetCouleur = RGB(255, 255, 255) ' Blanc
        Case 15 To 21
            GetCouleur = RGB(255, 0, 0) ' Rouge
        ' Ajoutez d'autres cas ici en fonction de vos besoins
        Case Else
            GetCouleur = RGB(0, 0, 0) ' Noir par défaut
    End Select
End Function

But it's wrong

1

There are 1 answers

4
taller On

Create it with ColorIndex

Sub ColorSqu()
    Dim r As Long, c As Long
    Cells.RowHeight = 25.8
    Cells.ColumnWidth = 4.4
    Cells.HorizontalAlignment = xlCenter
    For r = 1 To 8
        For c = 1 To 7
            With Cells(r, c)
                .Value = 7 * (r - 1) + c
                .Interior.ColorIndex = .Value
                If r + c = 2 Then .Font.Color = vbWhite
            End With
        Next
    Next
End Sub