VBA存储RGB颜色在变量 [英] VBA store RGB colour in variable
问题描述
我想在Excel VBA项目的变量中存储一个RGB颜色,用于设置各个单元格/范围的背景颜色。
I'm looking to store an RGB colour in a variable in an Excel VBA project, to be used to set the background color of various cell/ranges throughout a sub.
我想在变量中设置颜色一次,所以如果我决定改变它,我只需要在一个地方做。
I want to set the colour once in a variable, so that if I decide to change it throughout I only need to do it in one place.
但我尝试以下操作无效:
However my attempt below isn't working:
Dim clrBlue As ColorFormat
clrBlue = RGB(0, 0, 256)
Range("a2").Interior.Color = clrBlue
Range("b3").Interior.Color = clrBlue
使用上面的代码,我得到一个变量未设置
运行时错误。
With the above code, I get an Object variable or With block variable not set
runtime error.
我觉得我做的事根本错了!任何人都可以建议它是什么?可以这样做吗?
I feel I'm doing something fundamentally wrong! Can anyone suggest what it is? Can this even be done?
在写这篇文章的时候,我意识到我可以编写单独的函数( SetBlue
, SetRed
, SetGreen
)应用每种颜色,但只是觉得凌乱。
In writing this I realise I could write separate functions (SetBlue
, SetRed
, SetGreen
)to apply each colour, but that just feels messy.
推荐答案
RGB
返回 code>,因此您需要将
clrBlue
声明为 Long
,而不是 ColorFormat
。
RGB
returns a Long
, so you need to declare clrBlue
as Long
instead of as ColorFormat
.
Dim clrBlue As Long
clrBlue = RGB(0, 0, 256)
Application.union(Range("A2"), Range("B3")).Interior.Color = clrBlue
这篇关于VBA存储RGB颜色在变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!