如何使用 VBA 设置 Excel 单元格的背景颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/365125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I set the background color of Excel cells using VBA?
提问by paxdiablo
As part of a VBA program, I have to set the background colors of certain cells to green, yellow or red, based on their values (basically a health monitor where green is okay, yellow is borderline and red is dangerous).
作为 VBA 程序的一部分,我必须根据它们的值将某些单元格的背景颜色设置为绿色、黄色或红色(基本上是一个健康监视器,其中绿色可以,黄色是边界,红色是危险的)。
I know how to set the values of those cells, but how do I set the background color.
我知道如何设置这些单元格的值,但如何设置背景颜色。
回答by Vinko Vrsalovic
You can use either:
您可以使用:
ActiveCell.Interior.ColorIndex = 28
or
或者
ActiveCell.Interior.Color = RGB(255,0,0)
回答by Jon Crowell
This is a perfect example of where you should use the macro recorder. Turn on the recorder and set the color of the cells through the UI. Stop the recorder and review the macro. It will generate a bunch of extraneous code, but it will also show you syntax that works for what you are trying to accomplish. Strip out what you don't need and modify (if you need to) what's left.
这是您应该在何处使用宏记录器的完美示例。打开记录器并通过 UI 设置单元格的颜色。停止录音机并查看宏。它会生成一堆无关的代码,但它也会向您展示适用于您要完成的任务的语法。去掉你不需要的东西并修改(如果你需要的话)剩下的东西。
回答by Jon Crowell
or alternatively you could not bother coding for it and use the 'conditional formatting' function in Excel which will set the background colour and font colour based on cell value.
或者,您可以不费心为它编码并使用 Excel 中的“条件格式”功能,该功能将根据单元格值设置背景颜色和字体颜色。
There are only two variables here so set the default to yellow and then overwrite when the value is greater than or less than your threshold values.
这里只有两个变量,因此将默认值设置为黄色,然后在值大于或小于阈值时覆盖。
回答by Matt G
Do a quick 'record macro' to see the color number associated with the color you're looking for (yellow highlight is 65535). Then erase the code and put
执行快速“记录宏”以查看与您要查找的颜色相关联的颜色编号(黄色突出显示为 65535)。然后擦除代码并放入
Sub Name()
Selection.Interior.Color = 65535 '(your number may be different depending on the above)
End Sub
回答by user4700453
It doesn't work if you use Function, but works if you Sub. However, you cannot call a sub from a cell using formula.
如果您使用 Function,它不起作用,但如果您使用 Sub,它就起作用。但是,您不能使用公式从单元格中调用子项。

