gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 00:58:36 27 4
gpt4 key购买 nike

我有这段代码,显示目标单元格的 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 KB

A user-defined function called by a formula in a worksheet cell cannot change the environment of Microsoft Excel. This means that such a function cannot do any of the following: Insert, delete, or format cells on the spreadsheet.

不幸的是,这是不正确!!!

您可以更改调用公式的单元格的颜色。这是一个例子。这会将调用公式的单元格的颜色更改为红色

技巧是将空白值作为第一个参数传递给 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

屏幕截图

enter image description here

编辑(到期信用):我见过 this很久以前,蒂姆·威廉姆斯 (Tim Williams) 的帖子,我已经尝试过它,并且实现了许多其他知识库文章所说不可能的事情。

顺便说一句,我用它玩得更多,并且能够在不传递空白字符串的情况下使其工作。

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

编辑

来自 Duplicate question 的跟进和聊天(下面的评论)

将其粘贴到代码模块中,然后在单元格 P20 中粘贴公式 =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

enter image description here

注意:我没有进行任何错误处理。我相信你能处理好这个问题。

关于Excel:将单元格的背景颜色更改为该单元格中写入的 RGB 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31716565/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com