Excel VBA, RGB

As previously mentioned in the article Excel VBA, Color Code when working with colors in Excel you must know their color code. Though sometimes you may want set the color by using the RGB color model. This can be achieved using the RGB() function. For more information about the RGB model please see RGB Color Model.

The RGB() function receives 3 integers as input. The amount of Red, Green and Blue in the color. The values are between 0 and 255. The RGB() function returns the color code associated with the input parameters.


Syntax:

ColorCode = RGB(Red, Green, Blue)

Red: Integer determining the amount of Red in the color (0~255)

Green: Integer determining the amount of Green in the color (0~255)

Blue: Integer determining the amount of Blue in the color(0~255)

ColorCode: A Long value determining the color code assiociated with the input parameters.


Example

In this example the user inputs the amount of Red, Blue and Green in cell A2, B2 and C2. The fill color of cell D2 is updates with the color code returned by the RGB() function. Below you can see some examples:

Red = 0, Green = 0, Blue = 0:

Excel VBA, RGB, 0, 0, 0
Red = 255, Green = 0, Blue = 0:

Excel VBA, RGB, 255, 0, 0
Red = 255, Green = 255, Blue = 0:

Excel VBA, RGB, 255, 255, 0
Red = 255, Green = 115, Blue = 115:

Excel VBA, RGB, 255, 115, 115
The program uses a Worksheet_Change event handler. The event handler executes whenever the user inputs a new value:

'executes whenever the user inputs new values in the sheet
Private Sub Worksheet_Change(ByVal target As Range)
'changes the color of cell D2 to the color determined
'by the red, green and blue parameters
Range("D2").Interior.Color = RGB(Cells(2, 1), _
Cells(2, 2), Cells(2, 3))
End Sub

You can download the file and code related to this article here.

See also:

If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website www.software-solutions-online.com

Leave a Reply

Your email address will not be published. Required fields are marked *

privacy policy