Excel:将单元格的背景颜色更改为写入该单元格的RGB颜色

我有这个代码显示目标单元格的RGB颜色:

Function getRGB(RefCell) Dim mystr As String Application.Volatile mystr = Right("000000" & Hex(RefCell.Interior.Color), 6) getRGB = Application.Hex2Dec(Right(mystr, 2)) & ", " & _ Application.Hex2Dec(Mid(mystr, 3, 2)) & ", " & _ Application.Hex2Dec(Left(mystr, 2)) End Function 

我需要这个代码,而不是显示其他单元格的RGB,将改变自己的单元格的背景颜色。 也许有人知道如何做到这一点?

MSDN知识库说

由工作表单元格中的公式调用的用户定义的函数不能更改Microsoft Excel的环境。 这意味着这样的函数不能执行以下任何操作:在电子表格中插入,删除或格式化单元格。

不幸的是不正确的

您可以更改公式所在的单元格的颜色。 这是一个例子。 这会将单元格的颜色从公式所在的位置更改为Red

诀窍是将一个空白值作为第一个parameter passing给sub(在下面的例子中是a )。

为什么它工作?

我不知道! 但它的作品:)

 Function SetIt(RefCell) RefCell.Parent.Evaluate "getRGB(" & """""" & "," & RefCell.Address(False, False) & ")" SetIt = "" End Function Sub getRGB(a As String, RefCell As Range) RefCell.Interior.ColorIndex = 3 '<~~ Change color to red End Sub 

截图

在这里输入图像说明

编辑 (Credit Due Due):很久以前我曾经看过Tim Williams的这个主题,我曾经尝试过,而且我已经获得了许多其他知识库文章所说的东西是不可能的。

顺便说一句,我玩的更多,我能够使其工作,没有通过一个空白的string。

 Function SetIt(RefCell) RefCell.Parent.Evaluate "getRGB(" & RefCell.Address(False, False) & ")" SetIt = "" End Function Sub getRGB(RefCell As Range) RefCell.Interior.ColorIndex = 3 End Sub 

编辑

跟进重复的问题和聊天(下面的评论)

将其粘贴到代码模块中,然后在单元格P20粘贴formula =setit(P20,N20)

 Function SetIt(DestCell As Range, RefCell As Range) RefCell.Parent.Evaluate "SetAndGetRGB(" & RefCell.Address(False, False) & _ "," & _ DestCell.Address(False, False) & ")" SetIt = "" End Function Sub SetAndGetRGB(RefCell As Range, DestCell As Range) Dim sRGB As String Dim shName As String shName = Split(RefCell.Value, "!")(0) sRange = Split(RefCell.Value, "!")(1) sRGB = Right("000000" & Hex(Sheets(shName).Range(sRange).Interior.Color), 6) DestCell.Interior.Color = RGB( _ Application.Hex2Dec(Right(sRGB, 2)), _ Application.Hex2Dec(Mid(sRGB, 3, 2)), _ Application.Hex2Dec(Left(sRGB, 2)) _ ) End Sub 

在这里输入图像描述

注意 :我没有做任何error handling。 我相信你可以照顾的。

由于不能使用被称为UDF的函数来设置单元格的颜色,因此您需要使用一个sub。

很简单的例子:

 Function CopyColor(RefCell As Range, DestCell As Range) DestCell.Interior.Color = RefCell.Interior.Color End Function 

Siddharth的解决scheme看起来不错。 如果你希望在input公式的时候有这样的function,把这个代码放在VBA页面上。 每当内容发生变化时,它将检查单元格中的更改,如果内容对应于颜色格式,则可以使用它更改颜色:

 Private Sub Worksheet_Change(ByVal Target As Range) ' Test if a cell contains the proper formatting ' If it does, assign color Target.Interior.ColorIndex = Target.Value End Sub