Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the background color of Excel cells using VBA?

Tags:

excel

vba

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).

I know how to set the values of those cells, but how do I set the background color.

like image 321
paxdiablo Avatar asked Dec 13 '08 11:12

paxdiablo


People also ask

How do I change the background in VBA?

In the VBA Editor, from the Tools menu, select Options and then select the Editor Format tab. In the list of Code Colors, select 'Normal Text'. From the Foreground dropdown list, select 'Yellow'. From the Background dropdown list select 'Black'.


2 Answers

You can use either:

ActiveCell.Interior.ColorIndex = 28 

or

ActiveCell.Interior.Color = RGB(255,0,0) 
like image 165
Vinko Vrsalovic Avatar answered Sep 28 '22 03:09

Vinko Vrsalovic


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.

like image 37
Jon Crowell Avatar answered Sep 28 '22 02:09

Jon Crowell