This tutorial will show you how to fill a cell or a range using RGB color in Excel to create a gradient scale.
The first part of the article will be about how to fill a cell using the myRGB function. We will use the Excel COLOR function in the second part to return the selected cell’s color code. Both functions are UDFs (user-defined functions), and with their help, you can expand the default function library.
Generic Formula
Syntax:
=myRGB(red, green, blue)
Arguments:
The function uses three required arguments. Red, green, and blue are integers between 0 and 255.
How to fill a cell with RGB color
Here are the steps to fill a cell using RGB color:
- Use the Formula Bar to apply the =myRGB(R,G,B) function
- Enter the three required arguments (R, G, and B)
- Excel will fill the cell with the selected color
You can download the practice file that contains the myRGB function.
Here is the source code if you want to implement the function manually:
Option Explicit
Function myRGB(r, g, b)
Dim clr As Long, src As Range, sht As String, f, v
If IsEmpty(r) Or IsEmpty(g) Or IsEmpty(b) Then
clr = vbWhite
Else
clr = RGB(r, g, b)
End If
Set src = Application.ThisCell
sht = src.Parent.Name
f = "Changeit(""" & sht & """,""" & _
src.Address(False, False) & """," & clr & ")"
src.Parent.Evaluate f
myRGB = ""
End Function
Sub ChangeIt(sht, c, clr As Long)
ThisWorkbook.Sheets(sht).Range(c).Interior.Color = clr
End Sub
Generic formula to determine the Fill Color of a Cell
We will use the COLOR function in the example to return the selected cell color.
Syntax:
=COLOR(cell, return_type)
Arguments: the function uses one required and four optional arguments.
- 0 (default value) /optional
- 1: Hex /optional
- 2: RGB /optional
- 3: Excel color index
How to Retrieve Excel Cell’s Fill RGB Color Code
To determine the background color, use the COLOR function:
- Apply the COLOR function
- Select the cell that you want to determine the color
- Set “2” as a second argument to get the RGB color
- The function will return three comma-separated values.
Determine Excel Cell’s Fill Color Code (Hex, Excel color index, or integer)
Sometimes, we work with hexadecimal or integer format. In this case, use the following arguments:
- =COLOR(cell, 1) to get the hex color code
- =COLOR(cell, 3) to return with Excel color index
Function Color(rng As Range, Optional formatType As Integer = 0) As Variant
Dim cVal As Variant
cVal = rng.Cells(1, 1).Interior.Color
Select Case formatType
Case 1
Color = WorksheetFunction.Dec2Hex(cVal, 6)
Case 2
Color = (cVal Mod 256) & ", " & ((cVal \ 256) Mod 256) & ", " & (cVal \ 65536)
Case 3
Color = rng.Cells(1, 1).Interior.ColorIndex
Case Else
Color = cVal
End Select
End Function
Additional resources:
- Change shape color based on a cell value
- Color ranking in Excel
- Color combinations for Dashboards
- Fill color shortcut
- IF Statement Based on cell color