根据存储在其他单元格中的 RGB 值动态更改单元格的背景颜色

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

我正在尝试在 Excel 中编写一个函数,它将根据存储在其他三个单元格中的值设置活动单元格的背景颜色(这三个单元格中的每一个都存储一个从 0 开始的数值到 255,具体取决于颜色 R、G 或 B)。

所以 A1 单元格是 150,B1 单元格是 220,C1 单元格是 90(即 RGB(150, 220, 90))。我需要 D1 单元格的颜色是之前声明的 RGB(某种绿色),而且,如果我将函数放在 D2 中,它将 select RGB 存储在 A2、B2 和 C2 中,依此类推...

这能实现吗?

D1中输入:

=A1 & "," & B1 & "," & C1

并在工作表代码区域中,输入以下事件宏:

Private Sub Worksheet_Calculate()
   Range("D1").Interior.Color = RGB(Range("A1"), Range("B1"), Range("C1"))
End Sub

假设您希望它适用于整个列而不只是第 1 行,这里是工作表代码模块的 VBA 过程:

Private Sub Worksheet_Change(ByVal Target As Range)

    With Target
        If .Count = 1 Then
            If .Column < 4 Then
                Cells(.Row, 4).Interior.Color = RGB(Cells(.Row, 1), Cells(.Row, 2), Cells(.Row, 3))
            End If
        End If
    End With

End Sub

注意:我不知道您所说的以下内容是什么意思,所以没有解决它:and also, if I place the function in D2, it will select the RGB stored in A2, B2 and C2

UDF 版本:

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

用法(在 D1 中输入):

=myRGB(A1,B1,C1)

我想详细说明蒂姆·威廉姆斯的精彩回答。我需要能够根据其他单元格在我的单元格中显示十六进制值。因此,我还希望将字体设置为白色或黑色。所以我修改了函数如下:

Function hexColor(r, g, b)

    Dim bclr As Long, fclr As Long, src As Range, sht As String, f, v

     If IsEmpty(r) Or IsEmpty(g) Or IsEmpty(b) Then
        bclr = vbWhite
        fclr = vbBlack
    Else
        bclr = RGB(r, g, b)
        If ((r * 0.299) + (g * 0.587) + (b * 0.114) > 186) Then
            fclr = vbBlack
        Else
            fclr = vbWhite
        End If
    End If

    Set src = Application.ThisCell
    sht = src.Parent.Name

    f = "Changeit(""" & sht & """,""" & _
                  src.Address(False, False) & """," & bclr & "," & fclr & ")"
    src.Parent.Evaluate f

    Dim hr As String, hg As String, hb As String

    hr = Right("0" & Hex(r), 2)
    hg = Right("0" & Hex(g), 2)
    hb = Right("0" & Hex(b), 2)

    hexColor = "#" & hr & hg & hb
End Function

Sub ChangeIt(sht, c, bclr As Long, fclr As Long)
    ThisWorkbook.Sheets(sht).Range(c).Interior.Color = bclr
    ThisWorkbook.Sheets(sht).Range(c).Font.Color = fclr
End Sub

这意味着我可以输入以下两个单元格值:=hexColor(185,201,225)=hexColor(115,146,198) 并得到以下结果: