VBA Excel RGB Property and get RGB Color

What does VBA Excel RGB Property do?

VBA Excel RGB Property is a color Property of Objects, commonly used for Cell color or Shape color.

“RGB” stands for Red Green Blue, which are known as three additive primary colors, which can be combined to produce other colors. For example, purple is a mix of blue and red.  In RGB Property, you need to give a value (from 0 to 255) for each color in order to mix a new color. For example, Red = 255 means the brightness of color red is 100%.

rgb color

If you try to change a color but you don’t know the color code, you can visit the websites below

http://www.ifreesite.com/color/

http://big-coronasdklua.blogspot.hk/2011/04/rgb.html

You may also want to compare ColorIndex Property with RGB Property to use a different Property to set color for Cells.

Syntax of VBA Excel RGB Property

expression.RGB(red, green, blue)

red Integer from 0-255
green Integer from 0-255
blue Integer from 0-255

Example of Excel VBA RGB Property

Example 1: Set Cell A1 font color to red

Range("A1").Font.Color = RGB(255, 0, 0)

Example 2: Set Cell A1 back color to red

Range("A1").Interior.Color = RGB(255, 0, 0)

Example 3: Set Cell A1 border color to red

Range("A1").Borders.Color = RGB(255, 0, 0)

Get RGB Color

Usually Property comes in a pair, one is to Set Property Method and another is  Get Property Method. However, RGB does not seem to have the Get Method.

To get the RGB Color, we need to get the use Interior.Color Property to get Interior Color first and then convert to RGB color based on the below formula

Interior Color = red+ green * 256 + blue * 256 ^ 2

Note carefully that if a Cell is colorless (no color), Interior.Color would return value 16777215, which is also the white color.

Below is a Function to get RGB color, where r, g, b are RGB value of Red, Green, Blue

Public Function wRGB(rng As Range)
 Dim intColor As Long
 Dim rgb As String
 intColor = rng.Interior.Color
 r = intColor And 255
 g = intColor \ 256 And 255
 b = intColor \ 256 ^ 2 And 255
 wRGB = r & "," & g & "," & b
End Function

2 thoughts on “VBA Excel RGB Property and get RGB Color

    1. When referring to the color of light (as opposed to paint), green is a primary color, and no it cannot be created by mixing two other colors of light.

Leave a Reply

Your email address will not be published.