Vba excel rgb colors

Заливка ячейки цветом в VBA Excel. Фон ячейки. Свойства .Interior.Color и .Interior.ColorIndex. Цветовая модель RGB. Стандартная палитра. Очистка фона ячейки.

Свойство .Interior.Color объекта Range

Начиная с Excel 2007 основным способом заливки диапазона или отдельной ячейки цветом (зарисовки, добавления, изменения фона) является использование свойства .Interior.Color объекта Range путем присваивания ему значения цвета в виде десятичного числа от 0 до 16777215 (всего 16777216 цветов).

Заливка ячейки цветом в VBA Excel

Пример кода 1:

Sub ColorTest1()

Range(«A1»).Interior.Color = 31569

Range(«A4:D8»).Interior.Color = 4569325

Range(«C12:D17»).Cells(4).Interior.Color = 568569

Cells(3, 6).Interior.Color = 12659

End Sub

Поместите пример кода в свой программный модуль и нажмите кнопку на панели инструментов «Run Sub» или на клавиатуре «F5», курсор должен быть внутри выполняемой программы. На активном листе Excel ячейки и диапазон, выбранные в коде, окрасятся в соответствующие цвета.

Есть один интересный нюанс: если присвоить свойству .Interior.Color отрицательное значение от -16777215 до -1, то цвет будет соответствовать значению, равному сумме максимального значения палитры (16777215) и присвоенного отрицательного значения. Например, заливка всех трех ячеек после выполнения следующего кода будет одинакова:

Sub ColorTest11()

Cells(1, 1).Interior.Color = 12207890

Cells(2, 1).Interior.Color = 16777215 + (12207890)

Cells(3, 1).Interior.Color = 4569325

End Sub

Проверено в Excel 2016.

Вывод сообщений о числовых значениях цветов

Числовые значения цветов запомнить невозможно, поэтому часто возникает вопрос о том, как узнать числовое значение фона ячейки. Следующий код VBA Excel выводит сообщения о числовых значениях присвоенных ранее цветов.

Пример кода 2:

Sub ColorTest2()

MsgBox Range(«A1»).Interior.Color

MsgBox Range(«A4:D8»).Interior.Color

MsgBox Range(«C12:D17»).Cells(4).Interior.Color

MsgBox Cells(3, 6).Interior.Color

End Sub

Вместо вывода сообщений можно присвоить числовые значения цветов переменным, объявив их как Long.

Использование предопределенных констант

В VBA Excel есть предопределенные константы часто используемых цветов для заливки ячеек:

Предопределенная константа Наименование цвета
vbBlack Черный
vbBlue Голубой
vbCyan Бирюзовый
vbGreen Зеленый
vbMagenta Пурпурный
vbRed Красный
vbWhite Белый
vbYellow Желтый
xlNone Нет заливки

Присваивается цвет ячейке предопределенной константой в VBA Excel точно так же, как и числовым значением:

Пример кода 3:

Range(«A1»).Interior.Color = vbGreen

Цветовая модель RGB

Цветовая система RGB представляет собой комбинацию различных по интенсивности основных трех цветов: красного, зеленого и синего. Они могут принимать значения от 0 до 255. Если все значения равны 0 — это черный цвет, если все значения равны 255 — это белый цвет.

Выбрать цвет и узнать его значения RGB можно с помощью палитры Excel:

Палитра Excel

Палитра Excel

Чтобы можно было присвоить ячейке или диапазону цвет с помощью значений RGB, их необходимо перевести в десятичное число, обозначающее цвет. Для этого существует функция VBA Excel, которая так и называется — RGB.

Пример кода 4:

Range(«A1»).Interior.Color = RGB(100, 150, 200)

Список стандартных цветов с RGB-кодами смотрите в статье: HTML. Коды и названия цветов.

Очистка ячейки (диапазона) от заливки

Для очистки ячейки (диапазона) от заливки используется константа xlNone:

Range(«A1»).Interior.Color = xlNone

Свойство .Interior.ColorIndex объекта Range

До появления Excel 2007 существовала только ограниченная палитра для заливки ячеек фоном, состоявшая из 56 цветов, которая сохранилась и в настоящее время. Каждому цвету в этой палитре присвоен индекс от 1 до 56. Присвоить цвет ячейке по индексу или вывести сообщение о нем можно с помощью свойства .Interior.ColorIndex:

Пример кода 5:

Range(«A1»).Interior.ColorIndex = 8

MsgBox Range(«A1»).Interior.ColorIndex

Просмотреть ограниченную палитру для заливки ячеек фоном можно, запустив в VBA Excel простейший макрос:

Пример кода 6:

Sub ColorIndex()

Dim i As Byte

For i = 1 To 56

Cells(i, 1).Interior.ColorIndex = i

Next

End Sub

Номера строк активного листа от 1 до 56 будут соответствовать индексу цвета, а ячейка в первом столбце будет залита соответствующим индексу фоном.

Подробнее о стандартной палитре Excel смотрите в статье: Стандартная палитра из 56 цветов, а также о том, как добавить узор в ячейку.


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)

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

Excel VBA RGB Color

RGB can also be called red, green, and blue. So, one may use this function to get the numerical value of the color value. This function has three components as a named range, and they are red, blue, and green. The other colors are the components of these three different colors in VBA.

In VBA, everything boils down to the coding of every piece. For example, we can use the RANGE object if you want to reference some portion of the worksheet. If you want to change the font color, we can use the NAME property of the range. Then, write the font name that we need but imagine a situation of changing the font color or the cell’s background color. Of course, we can use built-in VB colors like vbGreen, vbBlue, vbRed, etc. But, we have a dedicated function to play around with different colors, i.e., RGB.

Table of contents
  • Excel VBA RGB Color
    • Change Color of Cells using VBA RGB Function
      • Example #1
      • Example #2
    • Things to Remember Here
    • Recommended Articles

VBA-RGB

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA RGB (wallstreetmojo.com)

Below is the syntax of the RGB color function.

VBA RGB Syntax

As you can see above, we can supply three arguments: red, green, and blue. These three parameters can only accept integer numbers ranging from 0 to 255. The result of this function will be the “Long” data type.

Change Color of Cells using VBA RGB Function

You can download this VBA RGB Excel Template here – VBA RGB Excel Template

Example #1

We have numbers from cells A1 to A8, as shown in the below image.

VBA RGB Example 1

We will try to change the font color to some random color for this range of cells by using the RGB function.

Start the macro procedure first.

Code:

Sub RGB_Example1()

End Sub

VBA RGB Example 1.0

First, we need to reference the range of cells of fonts we want to change the color of. In this case, our range of cells is A1 to A8, so supply the same  using the RANGE object.

Code:

Sub RGB_Example1()

  Range ("A1:A8")

End Sub

Example 1.2

Put a dot to see the IntelliSense list of RANGE objects. From the IntelliSense list, we are trying to change the font color, so choose the FONT property from the list.

Code:

Sub RGB_Example1()

  Range("A1:A8").Font

End Sub

VBA RGB Example 1.3

Once we chose the FONT property in this property, we tried to change the color, so we chose the color property of the FONT.

Code:

Sub RGB_Example1()

  Range("A1:A8").Font.Color

End Sub

Example 1.4

Put an equal sign and open the RGB function.

Code:

Sub RGB_Example1()

  Range("A1:A8").Font.Color = RGB(

End Sub

VBA RGB Example 1.5

Give random integer numbers ranging from 0 to 255 for all three arguments of the RGB function.

Code:

Sub RGB_Example1()

  Range("A1:A8").Font.Color = RGB(300, 300, 300)

End Sub

 Example 1.9

Now, run the code and see the result of font colors of the cells from A1 to A8.

Output:

VBA RGB Example 1.7.0

So, the colors of the font changed from black to some other. The color depends on the numbers we give to the RGB function.

Below are RGB color codes to get some of the common colors.

Example 1.8

You can just change the integer number combination from 0 to 255 to get the different sorts of colors.

Example #2

For the same range of cells, let us see how to change the background color of these cells.

First, supply the range of cells by using the RANGE object.

Code:

Sub RGB_Example2()

  Range ("A1:A8").

End Sub

VBA RGB Example 2

This time we are changing the background color of the mentioned cells, so we have nothing to do with the FONT property. Now, choose the “Interior” property of the RANGE object to change the background color.

Code:

Sub RGB_Example2()

  Range("A1:A8").Interior

End Sub

Example 2.1

Once the “Interior” property is selected, a dot to see the properties and methods of this “Interior” property.

Code:

Sub RGB_Example2()

  Range("A1:A8").Interior.

End Sub

VBA RGB Example 2.2

Since we are changing the interior color of the mentioned cells, choose the “Color” property.

Code:

Sub RGB_Example2()

  Range("A1:A8").Interior.Color

End Sub

Example 2.3

Set the interior color property of the range of cells (A1 to A8) out the equal sign and open the RGB function.

Code:

Sub RGB_Example2()

  Range("A1:A8").Interior.Color = RGB(

End Sub

VBA RGB Example 2.4

Enter the random number as you want.

Code:

Sub RGB_Example2()

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

End Sub

Example 2.6

Run the code and see the background color.

Output:

VBA RGB Example 2.5.0

The background color has changed.

Things to Remember Here

  • RGB stands for Red, Green, and Blue.
  • A combination of these three colors will give different colors.
  • All these three parameters can accept integer values between 0 to 255 only. It will reset any numbers above this to 255.

Recommended Articles

This article has been a guide to VBA RGB. Here, we discuss changing the color of the interior cell (background, font) in Excel VBA by putting different integer numbers in the RGB function with examples and a downloadable Excel template. Below are some useful Excel articles related to VBA: –

  • VBA Font Color
  • Excel VBA Web Scraping
  • Color Index in VBA
  • Class in VBA
  • VBA MsgBox (Yes/No)

In this Article

  • VBA Color Index Codes List
    • VBA ColorIndex Examples
  • VBA Color Property
  • VB Color
  • RGB Colors
  • ColorIndex Codes List & RGB Colors in Access VBA

VBA Color Index Codes List

When using VBA to code the Colorindex (or background color) of a cell it is useful to know what integer will equal what color. Below is a reference picture which shows the color and lists it’s respective Colorindex. aka VBA Color Palette

excel color references


Here’s the code to make one for yourself, or just bookmark this page:

Sub ColorRef()

Dim x As Integer

For x = 1 To 56
  If x < Then
    Cells(x, 1).Interior.ColorIndex = x
    Cells(x, 2) = x
  Else
    Cells(x - 28, 3).Interior.ColorIndex = x
    Cells(x - 28, 4) = x
  End If
Next x

End Sub

VBA ColorIndex Examples

Set Cell Background Color

This example sets the cell’s background color.

Range("A1").Interior.ColorIndex = 6

Set Cell Font Color

This example sets the cell’s font color.

Range("A1").Font.ColorIndex = 5

Set Cell Borders Color

This example sets the cell’s border color.

Range("A1").Borders.ColorIndex = 5

Get Cell Background ColorIndex

This example gets the cell’s background color and assigns it to an Integer variable.

Dim col as Integer

col = Range("A1").Interior.ColorIndex

Set a Cell Background Color to Another Cell’s Color

This example sets a cell color equal to another cell color.

Range("A1").Interior.ColorIndex  = Range("B1").Interior.ColorIndex

VBA Color Property

Instead of using Excel / VBA’s ColorIndex property, you can use the Color property. The Color property takes two input types:

  1. vbColor
  2. RGB Colors

We will discuss these below:

VB Color

VB Color is the easiest way to set colors in VBA. However, it’s also the least flexible.  To set a color code using vbColor use the table below:
vba vbcolor
However, as you can see from the table, your options are extremely limited.

Set Cell Background Color

Range("A1").Interior.Color = vbYellow

Set Cell Font Color

Range("A1").Font.Color = vbBlue

Set Cell Borders Color

Range("A1").Borders.Color = vbRed

Set a Cell Background Color to Another Cell’s Color

Range("A1").Interior.Color  = Range("B1").Interior.Color

RGB Colors

RGB stands for Red Green Blue. These are the three primary colors that can be combined to produce any other color. When entering colors as RGB, enter a value between 0 and 255 for each color code.

Here’s an example:

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

Above we’ve set Red = 255 (max value), Green = 255 (max value), and Blue = 0 (min value). This sets the cell background color to Yellow.

Instead we can set the cell font color to purple:

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

There are numerous online tools to find the RGB code for your desired color (here’s one).

ColorIndex Codes List & RGB Colors in Access VBA

Access uses forms to display data.  You can use the ColorIndex Codes to programmatically change the background color and foreground color of objects in your Access forms.

Private Sub cmdSave_Click()
'change the background color of the save button when the record is saved.
   DoCmd.RunCommand acCmdSaveRecord
   cmdSave.BackColor = vbGreen
End Sub

vba color change 1

VBA colors

0. Quick guide to the RGB color model

In this module:

  1. RGB color circles
  2. ColorIndex property — 56 colours, and VBA ColorConstants
  3. RGB and decimal color values, plus conversion
  4. Color property

The RGB color model adds combinations of Red, Green, and Blue to produce various colours. Each component is an integer value 0 to 255. The RGB colors with intersection overlap is demonstrated in figure 1.

1. RGB colors

1.1 RGB circles with additive colour mixing

Three RGB circles with colour mixing — returns 7 colors.

rgb circles

Fig 1: — three circles; Red, Green, and Blue (RGB), with 4 intersection points

With the inclusion of black (no colour), the eight colours are:

  1. Black: RGB(0,0,0)       
  2. White: RGB(255,255,255)       
  3. Red: RGB(255,0,0)       
  4. Green: RGB(0,255,0)       
  5. Blue: RGB(0,0,255)       
  6. Yellow: RGB(255,255,0)       
  7. Magenta: RGB(255,0,255)       
  8. Cyan: RGB(0,255,255)       

1.2 RGB circles — production code

Using web browser CSS and Scalable Vector Graphics (SVG)

Code for CSS style and Scalable Vector Graphics (SVG) used to produce the RGB circles in figure 1



    
    
    

	

2. VBA ColorIndex property

Syntax: expression.ColorIndex = value

where value is an element from the integer series 1,2, …, 56. Special values include xlColorIndexAutomatic (-4105) and xlColorIndexNone (-4142).

Examples of the ColorIndex property:

  • xlRange.Value = "excel"
  • xlRange.Interior.ColorIndex = 48
  • xlRange.Font.ColorIndex = 20
  • xlRange.Borders.ColorIndex = 3
  • xlRange.Characters(1, 2).Font.ColorIndex = 6

2.1 The 56 colours of ColorIndex

Colours 2 to 8 are red, green, and blue with additive mixing. The colours 9 to 56 are various combinations of red, green and blue with RGB values: 0, 51, 102, 128, 150, 153, 192, 204, and 255 (figure 2).

xlf-colindx2ws

Fig 2: ColorIndex — numbers, colours, and RGB values from code 1

The WS range in figure 2 was printed from the ColIndx2wWS procedure in code 1.

Code 1: Sub ColIndx2WS procedure prints ColorIndex to WS (see figure 2)

Sub ColIndx2WS()
' Requires xlfDec2RGB(ColDec) function
Dim i As Integer
Dim AC As Range: Set AC = ActiveCell

    For i = 1 To 56
        AC(i, 1) = i
        AC(i, 1).HorizontalAlignment = xlLeft
        AC(i, 2).Interior.ColorIndex = i
        AC(i, 3).Value = "RGB(" & xlfDec2RGB(AC(i, 2).Interior.Color) & ")"     ' see code ...
        AC(i, 3).HorizontalAlignment = xlRight
    Next i
    AC(i, 3).ColumnWidth = 19
End Sub

The colour table can also be printed as a 7 by 8 array (code 2)

Fig 3: — VBA ColorIndex 56 colors, 7 x 8 array

Code 2: Sub ColIndx2WSarraS procedure prints ColorIndex to WS array (7 rows by 8 columns)

Sub ColIndx2WSarray()
Const TLC As String = "B2"      ' top left cell
Dim i As Integer, j As Integer
Dim Col As Integer, Val As Integer

    With Range(TLC)
    For i = 1 To 7
        For j = 1 To 8
            Col = i * j
            Val = Val + 1
            .Offset(i - 1, j - 1).Interior.ColorIndex = Col
            .Offset(i - 1, j - 1).Value = Val
            Select Case Col
                Case 1, 5, 9 To 14, 16, 18, 21, 23, 25, 29, 30, 32, 41, 47 To 49, 51 To 56
                    .Offset(i - 1, j - 1).Font.ColorIndex = 2
                Case Else
                    .Offset(i - 1, j - 1).Font.ColorIndex = 1
            End Select
        Next j
    Next i
        .Resize(7, 8).ColumnWidth = 5
        .Resize(7, 8).RowHeight = 20
    End With

End Sub

Ten of the ColorIndex colours are duplicate pairs:
Blue    5    and    32   ;
Yellow    6    and    27   ;
Pink    7    and    26   ;
Turquoise    8    and    28   ;
Dark Red    9    and    30   ;
Dark Blue    11    and    25   ;
Violet    13    and    29   ;
Teal    14    and    31   ;
[No name]    18    and    54   ;
and [No name]    20    and    34   
. Leaving only 46 unique colours.

2.2 ColorConstants

The 8 colours listed in section 1.1 have name equivalents listed as members of the VBA ColorConstants class in the decimal colour system. The ColorConstants Auto List drop down is shown in figure 4.

media/xlf-vba-colorconstants

Fig 4: VBA ColorConstants — VBA Auto List drop down with 8 items

Code 3 prints a list of the ColorConstants numerical values to the immediate window (figure 5).

Code 3: Sub ColConst procedure

Sub ColConst()
Dim i As Integer
Dim ColArrVal As Variant
Dim ColArrLbl As Variant

    ColArrVal = Array(vbBlack, vbWhite, vbRed, vbGreen, vbBlue, vbYellow, vbMagenta, vbCyan)
    ColArrLbl = Array("vbBlack", "vbWhite", "vbRed", "vbGreen", "vbBlue", "vbYellow", "vbMagenta", "vbCyan")

    For i = LBound(ColArrVal) To UBound(ColArrVal)
        Debug.Print ColArrLbl(i) & ": " & ColArrVal(i)
    Next i

End Sub

The immediate window with output from line 69

media/xlf-colorconstants-decimal

Fig 5: VBA ColorConstants — colors 1 to 8

3. Decimal values of colours

3.1 RGB to positive decimal

To convert RGB to decimal
, the relationship is (C_d = R * 256 ^ 0 + (G * 256 ^ 1) + (B * 256 ^ 2)). See code 4.

Code 4: Function xlfRGB2DecX converts RGB values to decimal. Includes test routine

Function xlfRGB2DecX(Red As Integer, Green As Integer, Blue As Integer) As Long
    xlfRGB2DecX = Red * 256 ^ 0 + Green * 256 ^ 1 + Blue * 256 ^ 2
End Function

' ===========================
Function xlfRGB2DecY(Red As Integer, Green As Integer, Blue As Integer) As Long
    xlfRGB2DecY = RGB(Red, Green, Blue)
End Function

' ===========================
Sub TestxlfRGB2DecX()
Dim Ans As Long
    Ans = xlfRGB2DecX(204, 255, 255)
End Sub

3.2 RGB to negative decimal

To convert RGB to Excel negative decimal, the relationship is (C_{-d} = RGB — (256^3) — 1 )

The color red is RGB(255,0,0), equal to 256 as a positive value. The Excel negative value equivalent is RGB — (256^3) — 1 = 256 - (256^3) - 1 = -16776961

3.3 Decimal to RGB

The backslash operator «» divides two numbers and returns the integer quotient. The remainder is ignored.

Code 5: Function xlfDec2RGB converts color decimal to RGB comma separated values. Includes test routine

Function xlfDec2RGB(ByVal ColDec As Long) As String
Dim R As Long
Dim G As Long
Dim b As Long

  R = (ColDec And &HFF)  256 ^ 0      ' &HFF hexadecimal = 255 decimal
                                       ' leading &H is the prefix radix (base) for hexadecimal
  G = (ColDec And &HFF00&)  256 ^ 1   ' &HFF00& hexadecimal = 65280 decimal
                                       ' trailing & is a TDC for type long, if
                                       ' omitted (&HFF00), the assigned value is -256
  b = ColDec  256 ^ 2
  xlfDec2RGB = CStr(R) & "," & CStr(G) & "," & CStr(b)

End Function

' ===========================
Sub TestxlfDec2RGB()
Dim Ans As String
    Ans = xlfDec2RGB(16737843)  ' returns 51,102,255
    Stop
End Sub

About code 5

  • Line 95: 16737843 And 255 returns 51, 51 1 returns 51, remainder 0

    Further details of the binary And are provided in figure 5. Only the last 8 digits on the right are relevant.

    • 16737843 = 111111110110011000110011;
    • 255 = 11111111;
    • AND returns 00110011 = 51
  • xlf-binary-and
    Fig 5: binary AND — last 8 digits on the right
  • Line 97: 16737843 And 65280 returns 26112, 26112 256 returns 102, remainder 0
  • Line 100: 16737843 65536 returns 255, remainder 2616

4. Color property

Syntax: expression.Color = value

where value can be created by the RGB function returned as a long whole number.

Examples of the Color property:

  • xlRange.Value = "excel"
  • xlRange.Interior.Color = RGB(150,150,150) (equivalent to ColorIndex 48)
  • xlRange.Font.Color = 16777164 (equivalent to: RGB(204,255,255); ColorIndex 48)
  • xlRange.Borders.Color = RGB(150,0,0) (equivalent to ColorIndex 3)
  • xlRange.Characters(1, 2).Font.Color = 6 (equivalent to: RGB(6,0,0))
  • RGB discussion [23 Apr 2018]
  • Development platform: Excel 2016 64 bit.
  • Published: 14th April 2016
  • Revised: Friday 24th of February 2023 — 10:37 PM, Pacific Time (PT)

Понравилась статья? Поделить с друзьями:
  • Vba excel spinbutton пример
  • Vba excel replace пример
  • Vba excel sort key1
  • Vba excel replace in string
  • Vba excel soap запрос