Цвет ячейки rgb vba excel

Заливка ячейки цветом в 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 цветов, а также о том, как добавить узор в ячейку.


 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

#1

29.04.2015 12:39:26

Уважаемые форумчане, можно получить цвет заливки ячейки Excel таким образом:

Код
 Set R = Range("A1")
 x1 = R.Interior.Color 'в цифровом формате, например белый -"16777215"
 x2 = Hex$(x1) 'в шестнадцатеричном выражении - "FFFFFF" 
 x3 = "&H00" & x2 & "&" ' в формате H00+Hex - "&H00FFFFFF&" -используются в пользовательских формах Excel

Как получить в формате RGB (255,255,255), т.е. R=255, G=255, B=255?

Изменено: bedvit29.04.2015 12:45:13

«Бритва Оккама» или «Принцип Калашникова»?

 

Hugo

Пользователь

Сообщений: 23257
Регистрация: 22.12.2012

#2

29.04.2015 12:55:42

У себя в заметках нашёл такое (файл не качается…):

Код
Если необходимо вычислить RGB, то это делается так:
(фрагмент из файла Уокенбаха, пример здесь: http://www.planetaexcel.ru/docs/forum_upload/post_74452.xls)

Dim HexDigits As String
Dim BluePart As Integer, GreenPart As Integer, RedPart As Integer
UserForm1.SampleLabel.BackColor = ColorButton.BackColor
HexDigits = Hex(ColorButton.BackColor)
Do Until Len(HexDigits) = 6
HexDigits = "0" & HexDigits 'pad with zeros
Loop
BluePart = Val("&h" & Left(HexDigits, 2))
GreenPart = Val("&h" & Mid(HexDigits, 3, 2))
RedPart = Val("&h" & Right(HexDigits, 2))
UserForm1.RGBLabel.Caption = RedPart & " " & GreenPart & " " & BluePart

 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

#3

29.04.2015 14:06:53

Hugo, использовал Ваши данные, вышло следующее:

Код
...
Set R = Range("A1") 'вводим нужную ячейку
x1 = R.Interior.Color 'в цифровом формате, например белый -"16777215"
x2 = Hex$(x1) 'в шестнадцатеричном выражении - "FFFFFF"
Do Until Len(x2) = 6
x2 = "0" & x2 'догоняем 6 знаков нулями
DoEvents
Loop
x3 = "&H00" & x2 & "&" ' в формате H00+Hex - "&H00FFFFFF&" -используются в пользовательских формах Excel
R = Val("&h" & Right(x2, 2))
G = Val("&h" & Mid(x2, 3, 2))
B = Val("&h" & Left(x2, 2))
'Debug.Print R & " " & G & " " & B  'или MsgBox R & " " & G & " " & B    '-посмотреть... 
...

Спасибо!

Изменено: bedvit29.04.2015 14:10:22

«Бритва Оккама» или «Принцип Калашникова»?

 

Hugo

Пользователь

Сообщений: 23257
Регистрация: 22.12.2012

#4

29.04.2015 15:20:44

Не понял зачем там такое сложное

Код
Do Until Len(HexDigits) = 6
HexDigits = "0" & HexDigits 'pad with zeros
Loop

когда можно просто

Код
HexDigits = Right("000000" & HexDigits, 6)
 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

«Бритва Оккама» или «Принцип Калашникова»?

 

Слэн

Пользователь

Сообщений: 5192
Регистрация: 16.01.2013

#6

29.04.2015 16:05:07

так R.Interior.Color это запись rgb в виде (r+g*256+ b*256^2)

таким образом:

Код
Function rgb_(Rng)
Dim x, r, g, b
x = Rng.Interior.Color
b = Int(x / 65536)
x = x - b * 65536
g = Int(x / 256)
r = x - g * 256
rgb_ = "(" & r & "," & g & "," & b & ")"
End Function
Sub q()
ActiveCell.Interior.Color = rgb(125,128,200)
MsgBox rgb_(ActiveCell)
End Sub

Изменено: Слэн29.04.2015 16:07:08

Живи и дай жить..

 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

#7

29.04.2015 18:42:10

Слэн, отлично!
Hugo, Слэн, коллеги по Excel, кому интересна эта тема ))…
…набросал небольшую форму перевода из одной системы цветов в другую. (см. вложение)

Прикрепленные файлы

  • Цвет.xlsb (32.26 КБ)

Изменено: bedvit29.04.2015 18:45:42

«Бритва Оккама» или «Принцип Калашникова»?

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

  1. Свойство .Interior.Color объекта Range
    • Заливка ячейки цветом в VBA Excel
    • Вывод сообщений о числовых значениях цветов
    • Использование предопределенных констант
    • Цветовая модель RGB
  2. Свойство .Interior.ColorIndex объекта Range

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

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

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

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

1

2

3

4

5

6

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) и присвоенного отрицательного значения. Например, заливка
всех трех ячеек после выполнения следующего кода будет одинакова:

1

2

3

4

5

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:

1

2

3

4

5

6

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 Желтый

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

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

1

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

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

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

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

Палитра ExcelОткрывается в новом окне

Палитра Excel

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

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

1

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

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

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

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

1

2

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

MsgBox Range("A1").Interior.ColorIndex

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

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

1

2

3

4

5

6

Sub ColorIndex()

Dim i As Byte

For i = 1 To 56

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

Next

End Sub

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

Готовую стандартную палитру из 56 цветов можете посмотреть здесь .

Should note, for the hex values, if you’re exporting out to HTML you’re going to get quirks too.

Ideally you’d create the hex string from the individual colours, rather than returning a hex from the ColorVal number.

The reason being you can get some invalid hex numbers if the cell is a ‘pure’ colour like green/blue

RED — RGB(255,0,0) returns ‘FF’ — it should return ‘FF0000’

BLUE — RGB(0,0,255) returns ‘FF00000’ — it should return ‘0000FF’

enter image description here

If you used these to create HTML/CSS colour output, you’d get RED for any blue cells.

I modified the script to assemble each two character hex ‘chunk’ based on the RGB values, with a UDF that just pads with a leading 0 where output of one character is returned ( hopefully if you’re reading this, you can make something similar )

Color = ZeroPad(Hex((colorVal Mod 256)), 2) & ZeroPad(Hex(((colorVal  256) Mod 256)), 2) & ZeroPad(Hex((colorVal  65536)), 2)

—Edit : forgot to include the code for the UDF…

Function ZeroPad(text As String, Cnt As Integer) As String
'Text is the string to pad
'Cnt is the length to pad to, for example  ZeroPad(12,3) would return a string '012' , Zeropad(12,8) would return '00000012' etc..
Dim StrLen As Integer, StrtString As String, Padded As String, LP As Integer


StrLen = Len(Trim(text))


    If StrLen < Cnt Then

        For LP = 1 To Cnt - StrLen

            Padded = Padded & "0"

        Next LP

    End If

ZeroPad = Padded & Trim(text)

ENDOF:


End Function

BTW — If you want the hex codes as displayed in the form editor ( which inexplicably has it’s own standard , apart from the normal HTML Hex Colours )

    Case 4  ' ::: VBA FORM HEX :::
    Color = "&H00" & ZeroPad(Hex((colorVal  65536)), 2) &  ZeroPad(Hex(((colorVal  256) Mod 256)), 2) & ZeroPad(Hex((colorVal Mod 256)), 2) & "&"

You can start with this sub. It will color a range of your desire (Rc) with data from (Rs).

Sub ColorRGB(Rs As Range, Rc As Range)
Dim R As Long
Dim G As Long
Dim B As Long
Dim Address(1 To 3) As Long
Dim I As Integer: I = 1
For Each cell In Rs.Cells
Address(I) = cell.Value
I = I + 1
Next
R = Address(1)
G = Address(2)
B = Address(3)
Rc.Interior.Color = RGB(R, G, B)
End Sub

Test:

In this test, we’re coloring the cell D1 with the contents from the range A1:C1.

Sub Test()
ColorRGB Sheet1.Range("A1:C1"), Sheet1.Range("D1")
End Sub

Result:
enter image description here

The code below uses the RGBColor Sub. It will define a lastrow long (8 in our case) so this can basically handle more rows. Then, it will take the first vertical range of 8 cells and set it in a Range object called r only to do a For Each loop on it later.

With every cell in the For Each loop, we’re going to run with another For loop transversely (in direction of columns). The new For loop will run with step of 3 calling our ColorRGB function and telling it to take in the arguments supplied below.

Given the fact that the For loop runs with a step of 3, we’ve defined a counter for the colored cells called c that increments itself by 1 with each step of the For loop (its step is egal to 3).

I hope this logic is clear. There are obviously better methods to do this.

Sub ColorSheet(sheetname As string)
Dim r As Range
'defining lastrow which is 8
Dim lastrow As Long
With ThisWorkbook.Worksheets(sheetname)
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
Set r = .Range("A1", "A" & lastrow)
End With
Dim C As Integer: C = 30
For Each cell In r.Cells
For I = 1 To 30 Step 3
ColorRGB ThisWorkbook.Worksheets(sheetname).Range(cell.Offset(0, I - 1).Address(0, 0), cell.Offset(0, I + 1).Address(0, 0)), ThisWorkbook.Worksheets(sheetname).Range(cell.Offset(0, C).Address(0, 0))
C = C + 1
Next I
C = 30
Next
End Sub

This final sub will color the sheet name you provide it with.

Sub Test
ColorSheet("Sheet3")
'And so on...
End Sub

If your sheets are named like SheetX

    Sub Test
    Dim I as Integer
    For I = 1 to 20
    ColorSheet("Sheet"&I)
    Next I
    End Sub

Example:

enter image description here

VBA RGB

Excel VBA RGB

VBA RGB, where RGB can be expanded by Red, Green, and Blue. And this helps in changing the color of font and cell color as well. In VBA, every color is given a value by bifurcating its shades in red, green, and blue colors. And such we have a total of 56 shades of basic colors whose RGB values range from 0 to 255.

When we apply VBA RGB, we can apply either change the color cell background or we can change the font color. Below we have the syntax of VBA RGB.

VBA RGB Syntax

As we can see the syntax of RGB which clearly states that for each Red, Green, and Blue, it only considers the value as Integer. And together we can count RGB values as Long data type as well. We will be seeing the implementation of the RGB in upcoming examples. Before we move ahead, let’ see one of the basic colors which we could form using RGB as shown below.

VBA RGB Basic Colors

Change Color of background Cell Using RGB

We will learn how to change the color of the background cell in Excel by using the VBA Code.

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

Example #1

In this example, we will see the simplest way to use RGB in VBA. Before we move forward with our Excel VBA RGB Code, first let us have data that we will be using to change the color of their cell or fonts. Below we have listed on some number from cell A1 to A10, which we will be using this example. For this, follow the below steps:

VBA RGB Cells

Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.

Insert Module

Step 2: Now in the newly opened Module write the subprocedure of VBA RGB.

Code:

Sub VBA_RGB()

End Sub

VBA RGB Example 1-1

Step 3: First we will select the cells, whose color we want to change. Here our range of cell will be from A1 to A10.

Code:

Sub VBA_RGB()

Range("A1:A10").

End Sub

VBA RGB Example 1-2

Step 4: Now to change the color fonts of the selected cells, we will use the FONT function followed by COLOR.

Code:

Sub VBA_RGB()

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

End Sub

VBA RGB Example 1-3

Step 5: Now we will be using RGB with some random values to change the color Fonts from cell A1 to A10. We are giving more weightage to Red color and lesser to Green and Blue respectively as shown below.

Code:

Sub VBA_RGB()

Range("A1:A10").Font.Color = RGB(200, 100, 50)

End Sub

VBA RGB Example 1-4

Step 6: Now compile the code by pressing function key F8 and to run the code, click on the Play button located below the menu bar. We would see the color fonts of selected range cells nearer to Brown color.

VBA RGB Example 1-5

Example #2

In this example, we will be using the same data set which we saw in example-1 which is located in cell A1 to A10. Earlier we have seen the code to change the font colors but here we will be seeing how to change the color of a cell or background color or interior color. For this, again we can use the same line of code and do some editing or we can use a new module. We will be using the fresh module here. For this, follow the below steps:

Step 1: Open a new module and write the subprocedure for VBA RGB.

Code:

Sub VBA_RGB2()

End Sub

VBA RGB Example 2-1

Step 2: Now select the same sets of cell range from A1 to A10.

Code:

Sub VBA_RGB2()

Range("A1:A10").

End Sub

Range Example 2-2

Step 3: To change the interior color, we will be using the INTERIOR function along with COLOR in the same format which we saw in Example-1.

Code:

Sub VBA_RGB2()

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

End Sub

Interior Color Example 2-3

Step 4: Now we will be using RGB to fill the new color to the selected cell. We will be now giving more weightage to Green color and lesser to Red and Blue colors respectively.

Code:

Sub VBA_RGB2()

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

End Sub

VBA RGB Example 2-4

Step 5: Now compile the code by pressing function key F8 and to run the code, click on the Play button located below the menu bar. we will see the interior color of the selected cells is now changed to a major Green color.

Interior Color Example 2-5

Step 6: Let’s try to change and put the value of Green color more than 255 and see what color we get.

Code:

Sub VBA_RGB2()

Range("A1:A10").Interior.Color = RGB(0, 400, 50)

End Sub

VBA RGB Example 2-6

Step 7: Now again run this updated code. We will notice that interior color selected cells A1 to A10 remains unchanged like previous, which is because RGB value resets to 255 if we use value more than 255.

Interior Color Example 2-7

Pros of VBA RGB

  • It is so easy to change the font color and interior color using RGB with the help of code shown in the above examples.
  • We can create and fill any type of color in which we want to see a font or in the cell.
  • Using RGB we can automate the process of changing the color of cells or fonts which is quite useful to identify the difference of data.

Things to Remember

  • We can try any type of combination of Red, Green, and Blue colors in RGB to see different shades of color.
  • We can form any type of color using RGB in Excel VBA.
  • The value of any color parameter can only be between o and 255. If we try to use value more than 255, it would be reset to 255 again.
  • Always save the file in the Macro enable format to retain the written code to be used again multiple times.

Recommended Articles

This is a guide to the VBA RGB. Here we discuss how to change the color of background cell in Excel by using the VBA Code along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. How to Use VBA Login?
  2. VBA Month | Examples With Excel Template
  3. How to Use Create Object Function in VBA Excel?
  4. How to Use VBA IsError Function?
Skip to content

Excel VBA ColorIndex

  • VBA ColorIndex

VBA ColorIndex Property of Excel VBA is very useful to set the fill colors, border colors and font colors. Excel VBA ColorIndex returns index values from 1 to 56, -4105 and -4142. You can set the default colors using VBA enumeration number -4105 ( or xlColorIndexAutomatic). We can set VBA colorIndex -4142 (or xlColorIndexNone) enumeration to clear the colors or set to no colors.

Excel VBA ColorIndex

Syntax of Excel VBA ColorIndex

Here is the syntax of ColorIndex property of Excel VBA. You can set or return the color index value of the Excel Objects using the following VBA colorindex syntax.

expression.ColorIndex

Excel VBA Syntax to get the ColorIndex Value of the Excel Font, Interior or Border Color and store it in a Variable:

dblColorValue= expression.ColorIndex

Syntax to set the ColorIndex Value in Excel VBA to Excel Color Objects using Excel ColorIndex value:

expression.ColorIndex= IndexValue (1 to 56,-4105 or -4142)

ColorIndex in Excel VBA

Here are the list of Excel VBA ColorIndex Values and respective Colors:

ColorIndex Excel VBA Color ColorIndex Excel VBA Color
1 RGB(0,0,0) 29 RGB(128,0,128)
2 RGB(255,255,255) 30 RGB(128,0,0)
3 RGB(255,0,0) 31 RGB(0,128,128)
4 RGB(0,255,0) 32 RGB(0,0,255)
5 RGB(0,0,255) 33 RGB(0,204,255)
6 RGB(255,255,0) 34 RGB(204,255,255)
7 RGB(255,0,255) 35 RGB(204,255,204)
8 RGB(0,255,255) 36 RGB(255,255,153)
9 RGB(128,0,0) 37 RGB(153,204,255)
10 RGB(0,128,0) 38 RGB(255,153,204)
11 RGB(0,0,128) 39 RGB(204,153,255)
12 RGB(128,128,0) 40 RGB(255,204,153)
13 RGB(128,0,128) 41 RGB(51,102,255)
14 RGB(0,128,128) 42 RGB(51,204,204)
15 RGB(192,192,192) 43 RGB(153,204,0)
16 RGB(128,128,128) 44 RGB(255,204,0)
17 RGB(153,153,255) 45 RGB(255,153,0)
18 RGB(153,51,102) 46 RGB(255,102,0)
19 RGB(255,255,204) 47 RGB(102,102,153)
20 RGB(204,255,255) 48 RGB(150,150,150)
21 RGB(102,0,102) 49 RGB(0,51,102)
22 RGB(255,128,128) 50 RGB(51,153,102)
23 RGB(0,102,204) 51 RGB(0,51,0)
24 RGB(204,204,255) 52 RGB(51,51,0)
25 RGB(0,0,128) 53 RGB(153,51,0)
26 RGB(255,0,255) 54 RGB(153,51,102)
27 RGB(255,255,0) 55 RGB(51,51,153)
28 RGB(0,255,255) 56 RGB(51,51,51)

VBA to Print ColorIndex Table

Here is the Excel VBA Macro to print Excel ColorIndex Values and respective colors in Excel Sheet.
VBA to Print ColorIndex in Excel Range

Sub sbExcel_VBA_PrintColorIndex()
rowCntr = 2
colCntr = 2

For iCntr = 1 To 56

Cells(rowCntr, colCntr).Interior.ColorIndex = iCntr
Cells(rowCntr, colCntr) = iCntr
If iCntr > 1 And iCntr Mod 14 = 0 Then
    colCntr = colCntr + 1
    rowCntr = 2
Else
rowCntr = rowCntr + 1
End If

Next


End Sub

Set ColorIndex in Excel VBA

Here are the list of Excel VBA code to set ColorIndex to a Range of cells in Microsoft Excel Sheet.

Font Colors in Excel VBA

We can set the font colors in Excel VBA using ColorIndex property of Font Object. Here is the simple excel vba font color macro to set the font color of a given range A1:E20.

Sub SetFontColorIndex_Range()
    Range("A1:E20").Font.ColorIndex = 40
End Sub

You can also get the fornt colors using ColorIndex and store it in a variable. Please check the below code snippet:

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

This will return the font color and assign to a variable.

Interior Colors in Excel VBA

We can change the Interior or fill colors of a range using Excel VBA ColorIndex Property. Excel Interior Color macro heps you to change the interior color of an obect.

Sub SetInteriorColorIndex_Range()
    Range("A1:E20").Interior.ColorIndex = 41
End Sub

You can get Cell colors using Excel VBA, here is the get cell color excel vba macro to get the cell background colors.

myVar=Range("A1:E20").Interior.ColorIndex

Border Colors in Excel VBA

ColorIndex property of Borders is very easy to set the border colors in Excel VBA. Here is

Sub SetBordersColorIndex_Range()
Range("A1:E20").Borders.ColorIndex = 42
End Sub

Clear Colors in Excel VBA

Some times we need to fill no colors in Excel, we can clear the Excel Object colors such as font, border and fill colors and set to automatic or no fill color. Here are example macro to clear the color and fill no colors.

Clear Background Color in Excel VBA

We often required to clear the background or fill color of the excel object. We can use the following Excel Macro to clear the background colors and set no interior colors.

Sub SetClearBackgroundColor_ColorIndex_Range()
    Range("A1:E20").Interior.ColorIndex = -4142
End Sub

The above macro will set the Interior.ColorIndex to -4142 enumeration. Interior.ColorIndex = -4142 is enumeration to clear the background or fill color.

Similarly, we can clear the boder colors using Excel VBA as shown below:

Sub SetClearBorders_ColorIndex_Range()
    Range("A1:E20").Borders.ColorIndex = -4142
End Sub

We can set the font colors to default or automatic colors using Excel VBA ColorIndex property of Font object. Here is an example:

Sub SetClearFontColorIndex_Range()
    Range("A1:E20").Font.ColorIndex = -4105
End Sub

VBA Colors

We can set the colors in VBA using many approaches. We use ColorIndex Property, VBA Color Constants or set RGB Colors. We have already seen how to use ColorIndex in Excel VBA. Let us see the Excel VBA Color Constants and RGB Colors.

Excel VBA Color Constants

We can use the VBA Color Constants to set the colors of Excel Objects. Here is an easy to understand example:

Sub sbExcel_VBA_ColorConstants()
Cells(2, 4).Interior.Color = vbBlack
Cells(3, 4).Interior.Color = vbRed
Cells(4, 4).Interior.Color = vbGreen
Cells(5, 4).Interior.Color = vbYellow
Cells(6, 4).Interior.Color = vbBlue
Cells(7, 4).Interior.Color = vbMagenta
Cells(8, 4).Interior.Color = vbCyan
Cells(9, 4).Interior.Color = vbWhite

End Sub
VBA Color Constant VALUE Excel VBA Color & RGB
vbBlack 0x0 RGB(0,0,0)
vbRed 0xFF RGB(255,0,0)
vbGreen 0xFF00 RGB(0,255,0)
vbYellow 0xFFFF RGB(255,255,0)
vbBlue 0xFF0000 RGB(0,0,255)
vbMagenta 0xFF00FF RGB(255,0,255)
vbCyan 0xFFFF00 RGB(0,255,255)
vbWhite 0xFFFFFF RGB(255,255,255)

RGB Colors in Excel VBA

We have only few color codes when we use Constants or ColorIndex Property. RGB helps us to use all possible combination of colors with Red, Green and Blue. Here is a simple Excel macro to explain the RGB in VBA.

Sub ChangeBackgourdColorRGB_Range()
    Range("A1:E20").Interior.Color = rgb(125, 205, 99)
End Sub

RGB color can be any number between 0 and 255. Here are the list of RGB colors for Excel VBA ColorIndex color codes:
Excel VBA ColorIndex with RGB

Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates

Related Posts

  • Syntax of Excel VBA ColorIndex
  • ColorIndex in Excel VBA
    • VBA to Print ColorIndex Table
  • Set ColorIndex in Excel VBA
    • Font Colors in Excel VBA
    • Interior Colors in Excel VBA
    • Border Colors in Excel VBA
  • Clear Colors in Excel VBA
    • Clear Background Color in Excel VBA
  • VBA Colors
    • Excel VBA Color Constants
    • RGB Colors in Excel VBA

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

VBA Projects With Source Code

3 Realtime VBA Projects
with Source Code!

Take Your Projects To The Next Level By Exploring Our Professional Projects

Go to Top

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)

Понравилась статья? Поделить с друзьями:
  • Цвет ячейки excel миф
  • Цвет ячейки excel меняется сам
  • Цвет фона ячейки vba excel
  • Цвет фона ячеек excel
  • Цвет фона шрифта word