Search code examples
excelvbacolorshexrgb

How to make Colors Mixer in vba


The following link provides colors mixer in html.

https://www.w3schools.com/colors/colors_mixer.asp

I am looking for colors mixer code in vba.

Let me summarize what I want.

I will enter #FF0000 which is Red and enter #0000FF which is Blue into VBA. Then VBA will produce #8c0073 for me.

Please look at following picture in order to see which color I want to get.

Please Click Here


Solution

  • Maybe the following function is of any help

    Function GenerateGradient(color1 As String, color2 As String, steps As Integer) As String()
        Dim r1 As Long, g1 As Long, b1 As Long
        Dim r2 As Long, g2 As Long, b2 As Long
        Dim rStep As Double, gStep As Double, bStep As Double
        Dim i As Integer
        Dim r As Long, g As Long, b As Long
        Dim gradient() As String
        
        ' Convert color1 from hex to RGB
        r1 = CLng("&H" & Mid(color1, 2, 2))
        g1 = CLng("&H" & Mid(color1, 4, 2))
        b1 = CLng("&H" & Mid(color1, 6, 2))
        
        ' Convert color2 from hex to RGB
        r2 = CLng("&H" & Mid(color2, 2, 2))
        g2 = CLng("&H" & Mid(color2, 4, 2))
        b2 = CLng("&H" & Mid(color2, 6, 2))
        
        ' Calculate step increments
        rStep = (r2 - r1) / (steps - 1)
        gStep = (g2 - g1) / (steps - 1)
        bStep = (b2 - b1) / (steps - 1)
        
        ' Initialize the array to hold gradient values
        ReDim gradient(steps - 1)
        
        ' Generate the gradient
        For i = 0 To steps - 1
            r = r1 + rStep * i
            g = g1 + gStep * i
            b = b1 + bStep * i
            
            ' Convert RGB back to hex and store in the array
            gradient(i) = "#" & Right("00" & Hex(r), 2) & Right("00" & Hex(g), 2) & Right("00" & Hex(b), 2)
        Next i
        
        ' Return the gradient array
        GenerateGradient = gradient
    End Function
    

    You can test it like

    Sub GetMiddleColor()
        Dim gradient() As String
        Dim middleColor As String
        
        ' Generate 21 colors between Red and Blue
        gradient = GenerateGradient("#FF0000", "#0000FF", 21)
        
        ' Get the middle color (11th in the 21-element array, index 9 or 10)
        middleColor = gradient(9)
        Debug.Print middleColor
        ' Output the middle color
        MsgBox "Middle color in the gradient is: " & middleColor  ' Expected output: #8C0073
    End Sub