34

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.

5 Answers 5

75

You can use either:

ActiveCell.Interior.ColorIndex = 28

or

ActiveCell.Interior.Color = RGB(255,0,0)
Sign up to request clarification or add additional context in comments.

2 Comments

In the first example, how do you know which color the ColorIndex points to?
@awe - The colors and numbers are here: msdn.microsoft.com/en-us/library/cc296089(v=office.12).aspx
14

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.

Comments

2

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

Sub Name()
Selection.Interior.Color = 65535 '(your number may be different depending on the above)
End Sub

1 Comment

Maybe explain why and how a numeric literal can replace an RGB(,,) construct, and also possibly express the literal in hexadecimal Selection.Interior.Color = &H00FFFF where each pair of hexadecimal digits defines respectively the value of Red, Green and Blue in the range &H00 to &HFF.
1

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.

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.

Comments

-4

It doesn't work if you use Function, but works if you Sub. However, you cannot call a sub from a cell using formula.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.