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

时间:2015-10-16 20:59:01

标签: excel vba colors cell

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

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

这可以实现吗?

4 个答案:

答案 0 :(得分:13)

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)

答案 1 :(得分:4)

D1 中输入:

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

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

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

enter image description here

答案 2 :(得分:1)

假设您希望这可以使用整个列而不是第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

答案 3 :(得分:0)

我想补充一下蒂姆·威廉姆斯的绝妙答案。我需要能够根据其他单元格在我的单元格中显示一个十六进制值。因此,我也希望将字体设置为白色或黑色。所以我将功能修改如下:

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)并获得以下结果:

Excel sheet