Search code examples
excelvbacolorscell

Change a cell's background color dynamically according to a RGB value stored in other cells


I'm trying to write a function in Excel that will set the background color of the active cell according to the values stored in other three cells (each of those three cells store a numeric value from 0 to 255, depending on the color R, G or B).

So the A1 cell is 150, the B1 cell is 220 and the C1 cell is 90 (that's RGB(150, 220, 90)). I need that the D1 cell's color is that RGB declared before (some kind of green), and also, if I place the function in D2, it will select the RGB stored in A2, B2 and C2, and so on...

Can this be achieved?


Solution

  • UDF version:

    Function myRGB(r, g, b)
    
        Dim clr As Long, src As Range, sht As String, f, v
    
        If IsEmpty(r) Or IsEmpty(g) Or IsEmpty(b) Then
            clr = vbWhite
        Else
            clr = RGB(r, g, b)
        End If
    
        Set src = Application.ThisCell
        sht = src.Parent.Name
    
        f = "Changeit(""" & sht & """,""" & _
                      src.Address(False, False) & """," & clr & ")"
        src.Parent.Evaluate f
        myRGB = ""
    End Function
    
    Sub ChangeIt(sht, c, clr As Long)
        ThisWorkbook.Sheets(sht).Range(c).Interior.Color = clr
    End Sub
    

    Usage (entered in D1):

    =myRGB(A1,B1,C1)