Индексы цветов vba excel

Наименования цветов стандартной палитры Excel из 56 оттенков на русском и английском языках. Соответствие цветов индексам VBA и их RGB и HEX коды.

Стандартная палитра из 56 цветов — это ограниченная палитра оттенков, которая существовала до версии Excel 2007 года, но продолжает использоваться до сих пор.

За ограниченную палитру в VBA Excel отвечает свойство ColorIndex, которое используется для записи и чтения:

Sub Primer()

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

    MsgBox Range(«A1»).Interior.ColorIndex

End Sub

Свойство ColorIndex принимает и возвращает значения от 1 до 56.

Наименования 56 цветов палитры

Наименования 56 цветов стандартной ограниченной палитры Excel на русском и английском языках:

Индекс Наименование
по-русски
Наименование по-английски Оттенок
1 Черный Black
2 Белый White
3 Красный Red
4 Лайм Lime
5 Синий Blue
6 Желтый Yellow
7 Фуксия* Fuchsia*
8 Цвет морской волны Aqua
9 Темно-бордовый Maroon
10 Зеленый Green
11 Темно-синий Navy blue
12 Оливковый Olive
13 Пурпурный Purple
14 Бирюзовый Teal
15 Серебряный Silver
16 Серый Gray
17 Светло-пурпурно-синий Light purple blue
18 Розовато-лиловый Mauve
19 Бледно-желто-зеленый Pale yellow green
20 Бледно-голубой Pale blue
21 Сливовый Plum
22 Лососевый Salmon
23 Темно-сине-голубой Light navy blue
24 Барвинок Periwinkle
25 Темно-синий Navy blue
26 Фуксия* Fuchsia*
27 Желтый Yellow
28 Цвет морской волны Aqua
29 Пурпурный Purple
30 Коричнево-малиновый Maroon
31 Сине-зеленый Teal
32 Синий Blue
33 Небесно-голубой Vivid sky blue
34 Бледно-голубой Pale blue
35 Бледно-зеленый Pale green
36 Светло-желтый Light yellow
37 Сине-голубой Shade of blue
38 Бледно-пурпурно-розовый Pale magenta pink
39 Светло-сиреневый Light lilac
40 Оранжево-персиковый Peach-orange
41 Светло-синий Light blue
42 Светло-бирюзовый Light turquoise
43 Желто-зеленый Yellow green
44 Желтый мандарин Tangerine yellow
45 Сигнальный оранжевый Safety orange
46 Оранжевый Orange
47 Темно-сине-серый Dark blue gray
48 Светло-серый Light gray
49 Полуночно-синий Midnight blue
50 Зеленая трава Green grass
51 Темно-зеленый Dark green
52 Темно-коричневый Dark brown
53 Темно-красный Dark red
54 Розовато-лиловый Mauve
55 Синий пигмент Blue pigment
56 Темный уголь Dark charcoal

* Вместо термина Фуксия (Fuchsia) можно использовать термин Маджента (Magenta), так как в RGB-модели Фуксия и Маджента являются одним и тем же цветом.

Обратите внимание, что в стандартной палитре Excel из 56 цветов есть повторяющиеся оттенки. Наименования цветов (по их HEX-кодам) подобраны, главным образом, по статьям, опубликованным в Википедии.

RGB и HEX коды оттенков палитры

RGB и HEX коды оттенков 56-цветной палитры Excel:

Индекс Код HEX Код RGB Оттенок
1 #000000 RGB(0, 0, 0)
2 #ffffff RGB(255, 255, 255)
3 #ff0000 RGB(255, 0, 0)
4 #00ff00 RGB(0, 255, 0)
5 #0000ff RGB(0, 0, 255)
6 #ffff00 RGB(255, 255, 0)
7 #ff00ff RGB(255, 0, 255)
8 #00ffff RGB(0, 255, 255)
9 #800000 RGB(128, 0, 0)
10 #008000 RGB(0, 128, 0)
11 #000080 RGB(0, 0, 128)
12 #808000 RGB(128, 128, 0)
13 #800080 RGB(128, 0, 128)
14 #008080 RGB(0, 128, 128)
15 #c0c0c0 RGB(192, 192, 192)
16 #808080 RGB(128, 128, 128)
17 #9999ff RGB(153, 153, 255)
18 #993366 RGB(153, 51, 102)
19 #ffffcc RGB(255, 255, 204)
20 #ccffff RGB(204, 255, 255)
21 #660066 RGB(102, 0, 102)
22 #ff8080 RGB(255, 128, 128)
23 #0066cc RGB(0, 102, 204)
24 #ccccff RGB(204, 204, 255)
25 #000080 RGB(0, 0, 128)
26 #ff00ff RGB(255, 0, 255)
27 #ffff00 RGB(255, 255, 0)
28 #00ffff RGB(0, 255, 255)
29 #800080 RGB(128, 0, 128)
30 #800000 RGB(128, 0, 0)
31 #008080 RGB(0, 128, 128)
32 #0000ff RGB(0, 0, 255)
33 #00ccff RGB(0, 204, 255)
34 #ccffff RGB(204, 255, 255)
35 #ccffcc RGB(204, 255, 204)
36 #ffff99 RGB(255, 255, 153)
37 #99ccff RGB(153, 204, 255)
38 #ff99cc RGB(255, 153, 204)
39 #cc99ff RGB(204, 153, 255)
40 #ffcc99 RGB(255, 204, 153)
41 #3366ff RGB(51, 102, 255)
42 #33cccc RGB(51, 204, 204)
43 #99cc00 RGB(153, 204, 0)
44 #ffcc00 RGB(255, 204, 0)
45 #ff9900 RGB(255, 153, 0)
46 #ff6600 RGB(255, 102, 0)
47 #666699 RGB(102, 102, 153)
48 #969696 RGB(150, 150, 150)
49 #003366 RGB(0, 51, 102)
50 #339966 RGB(51, 153, 102)
51 #003300 RGB(0, 51, 0)
52 #333300 RGB(51, 51, 0)
53 #993300 RGB(153, 51, 0)
54 #993366 RGB(153, 51, 102)
55 #333399 RGB(51, 51, 153)
56 #333333 RGB(51, 51, 51)

RGB-коды можно использовать в VBA Excel наряду с индексами цветов стандартной палитры, а HEX-коды — в HTML.

Процент черного в оттенках серого

Процентное соотношение черного цвета в оттенках серого:

Индекс Наименование Процент черного Оттенок
1 Черный 100%
2 Белый 0%
15 Серебряный 25%
16 Серый 50%
48 Светло-серый 40%
56 Темный уголь 80%

Вывод 56-цветной палитры на лист

Вывод на рабочий лист Excel 56-цветной палитры с помощью кода VBA:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

‘Функция, преобразующая десятичный код цвета в аргументы RGB

Function DecToRGB(ByVal ColDec As Long) As String

Dim r As Long

Dim g As Long

Dim b As Long

    r = (ColDec And &HFF&) 256 ^ 0

    g = (ColDec And &HFF00&) 256 ^ 1

    b = ColDec 256 ^ 2

    DecToRGB = CStr(r) & «, « & CStr(g) & «, « & CStr(b)

End Function

‘Вывод 56-цветной палитры на активный лист

Sub Color56()

Dim i As Integer

    For i = 1 To 56

        Cells(i, 1) = i

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

        Cells(i, 3).Value = «RGB(« & DecToRGB(Cells(i, 2).Interior.Color) & «)»

    Next

End Sub

Процедура Color56 записывает в ячейку первого столбца индекс цвета, ячейке второго столбца присваивается соответствующая индексу заливка, в ячейку третьего столбца записывается RGB-код соответствующего индексу цвета.


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

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

Содержание

  1. Свойство ColorIndex (Excel Graph)
  2. Синтаксис
  3. Примечания
  4. Пример
  5. Поддержка и обратная связь
  6. VBA Excel. Цвет ячейки
  7. Свойство .Interior.Color объекта Range
  8. Заливка ячейки цветом в VBA Excel
  9. Вывод сообщений о числовых значениях цветов
  10. Использование предопределенных констант
  11. Цветовая модель RGB
  12. Свойство .Interior.ColorIndex объекта Range
  13. Excel VBA: ColorIndex Codes List & RGB Colors
  14. VBA Color Index Codes List
  15. VBA ColorIndex Examples
  16. Set Cell Background Color
  17. Set Cell Font Color
  18. Set Cell Borders Color
  19. Get Cell Background ColorIndex
  20. Set a Cell Background Color to Another Cell’s Color
  21. VBA Color Property
  22. VB Color
  23. Set Cell Background Color
  24. Set Cell Font Color
  25. Set Cell Borders Color
  26. Set a Cell Background Color to Another Cell’s Color
  27. RGB Colors
  28. ColorIndex Codes List & RGB Colors in Access VBA
  29. VBA Code Examples Add-in
  30. VBA Excel. Стандартная палитра из 56 цветов
  31. Стандартная палитра из 56 цветов
  32. Наименования 56 цветов палитры
  33. RGB и HEX коды оттенков палитры
  34. Процент черного в оттенках серого
  35. Вывод 56-цветной палитры на лист

Свойство ColorIndex (Excel Graph)

Возвращает или задает цвет границы, шрифта или внутренней области, как показано в следующей таблице. Цвет указывается в виде значения индекса в текущей цветовой палитре или в виде одной из следующих констант XlColorIndex: xlColorIndexAutomatic или xlColorIndexNone. Для чтения и записи, Variant.

Синтаксис

выражение. ColorIndex

выражение (обязательно). Выражение, возвращающее один из объектов списка Применяется к.

Примечания

Object Описание
Border Цвет границы.
Font Цвет шрифта.
Interior Цвет внутренней заливки. Присвойте параметру ColorIndex значение xlColorIndexNone, чтобы не применять внутреннюю заливку. Присвойте параметру ColorIndex значение xlColorIndexAutomatic, чтобы указать автоматическую заливку (для графических объектов).

Это свойство указывает цвет в виде индекса в цветовой палитре. На рисунке ниже показаны значения цветового индекса в цветовой палитре по умолчанию.

Пример

В следующих примерах предполагается, что используется цветовая палитра по умолчанию.

В этом примере устанавливается цвет основных линий сетки для оси значений.

В этом примере устанавливается красный цвет внутреннего заполнения диаграммы и синий цвет для границы.

Если вы хотите использовать цвет с объектом FormatCondition в Visual Basic, ознакомьтесь со статьей Свойство Interior.ColorIndex.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

VBA Excel. Цвет ячейки

Заливка ячейки цветом в 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:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Источник

Excel VBA: ColorIndex Codes List & RGB Colors

In this Article

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

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

VBA ColorIndex Examples

Set Cell Background Color

This example sets the cell’s background color.

Set Cell Font Color

This example sets the cell’s font color.

Set Cell Borders Color

This example sets the cell’s border color.

Get Cell Background ColorIndex

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

Set a Cell Background Color to Another Cell’s Color

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

VBA Color Property

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

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:

However, as you can see from the table, your options are extremely limited.

Set Cell Background Color

Set Cell Font Color

Set Cell Borders Color

Set a Cell Background Color to Another Cell’s 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:

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:

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.

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

VBA Excel. Стандартная палитра из 56 цветов

Наименования цветов стандартной палитры Excel из 56 оттенков на русском и английском языках. Соответствие цветов индексам VBA и их RGB и HEX коды.

Стандартная палитра из 56 цветов

За ограниченную палитру в VBA Excel отвечает свойство ColorIndex, которое используется для записи и чтения:

Свойство ColorIndex принимает и возвращает значения от 1 до 56.

Наименования 56 цветов палитры

Наименования 56 цветов стандартной ограниченной палитры Excel на русском и английском языках:

Индекс Наименование
по-русски
Наименование по-английски Оттенок
1 Черный Black
2 Белый White
3 Красный Red
4 Лайм Lime
5 Синий Blue
6 Желтый Yellow
7 Фуксия* Fuchsia*
8 Цвет морской волны Aqua
9 Темно-бордовый Maroon
10 Зеленый Green
11 Темно-синий Navy blue
12 Оливковый Olive
13 Пурпурный Purple
14 Бирюзовый Teal
15 Серебряный Silver
16 Серый Gray
17 Светло-пурпурно-синий Light purple blue
18 Розовато-лиловый Mauve
19 Бледно-желто-зеленый Pale yellow green
20 Бледно-голубой Pale blue
21 Сливовый Plum
22 Лососевый Salmon
23 Темно-сине-голубой Light navy blue
24 Барвинок Periwinkle
25 Темно-синий Navy blue
26 Фуксия* Fuchsia*
27 Желтый Yellow
28 Цвет морской волны Aqua
29 Пурпурный Purple
30 Коричнево-малиновый Maroon
31 Сине-зеленый Teal
32 Синий Blue
33 Небесно-голубой Vivid sky blue
34 Бледно-голубой Pale blue
35 Бледно-зеленый Pale green
36 Светло-желтый Light yellow
37 Сине-голубой Shade of blue
38 Бледно-пурпурно-розовый Pale magenta pink
39 Светло-сиреневый Light lilac
40 Оранжево-персиковый Peach-orange
41 Светло-синий Light blue
42 Светло-бирюзовый Light turquoise
43 Желто-зеленый Yellow green
44 Желтый мандарин Tangerine yellow
45 Сигнальный оранжевый Safety orange
46 Оранжевый Orange
47 Темно-сине-серый Dark blue gray
48 Светло-серый Light gray
49 Полуночно-синий Midnight blue
50 Зеленая трава Green grass
51 Темно-зеленый Dark green
52 Темно-коричневый Dark brown
53 Темно-красный Dark red
54 Розовато-лиловый Mauve
55 Синий пигмент Blue pigment
56 Темный уголь Dark charcoal

* Вместо термина Фуксия (Fuchsia) можно использовать термин Маджента (Magenta), так как в RGB-модели Фуксия и Маджента являются одним и тем же цветом.

Обратите внимание, что в стандартной палитре Excel из 56 цветов есть повторяющиеся оттенки. Наименования цветов (по их HEX-кодам) подобраны, главным образом, по статьям, опубликованным в Википедии.

RGB и HEX коды оттенков палитры

RGB и HEX коды оттенков 56-цветной палитры Excel:

Индекс Код HEX Код RGB Оттенок
1 #000000 RGB(0, 0, 0)
2 #ffffff RGB(255, 255, 255)
3 #ff0000 RGB(255, 0, 0)
4 #00ff00 RGB(0, 255, 0)
5 #0000ff RGB(0, 0, 255)
6 #ffff00 RGB(255, 255, 0)
7 #ff00ff RGB(255, 0, 255)
8 #00ffff RGB(0, 255, 255)
9 #800000 RGB(128, 0, 0)
10 #008000 RGB(0, 128, 0)
11 #000080 RGB(0, 0, 128)
12 #808000 RGB(128, 128, 0)
13 #800080 RGB(128, 0, 128)
14 #008080 RGB(0, 128, 128)
15 #c0c0c0 RGB(192, 192, 192)
16 #808080 RGB(128, 128, 128)
17 #9999ff RGB(153, 153, 255)
18 #993366 RGB(153, 51, 102)
19 #ffffcc RGB(255, 255, 204)
20 #ccffff RGB(204, 255, 255)
21 #660066 RGB(102, 0, 102)
22 #ff8080 RGB(255, 128, 128)
23 #0066cc RGB(0, 102, 204)
24 #ccccff RGB(204, 204, 255)
25 #000080 RGB(0, 0, 128)
26 #ff00ff RGB(255, 0, 255)
27 #ffff00 RGB(255, 255, 0)
28 #00ffff RGB(0, 255, 255)
29 #800080 RGB(128, 0, 128)
30 #800000 RGB(128, 0, 0)
31 #008080 RGB(0, 128, 128)
32 #0000ff RGB(0, 0, 255)
33 #00ccff RGB(0, 204, 255)
34 #ccffff RGB(204, 255, 255)
35 #ccffcc RGB(204, 255, 204)
36 #ffff99 RGB(255, 255, 153)
37 #99ccff RGB(153, 204, 255)
38 #ff99cc RGB(255, 153, 204)
39 #cc99ff RGB(204, 153, 255)
40 #ffcc99 RGB(255, 204, 153)
41 #3366ff RGB(51, 102, 255)
42 #33cccc RGB(51, 204, 204)
43 #99cc00 RGB(153, 204, 0)
44 #ffcc00 RGB(255, 204, 0)
45 #ff9900 RGB(255, 153, 0)
46 #ff6600 RGB(255, 102, 0)
47 #666699 RGB(102, 102, 153)
48 #969696 RGB(150, 150, 150)
49 #003366 RGB(0, 51, 102)
50 #339966 RGB(51, 153, 102)
51 #003300 RGB(0, 51, 0)
52 #333300 RGB(51, 51, 0)
53 #993300 RGB(153, 51, 0)
54 #993366 RGB(153, 51, 102)
55 #333399 RGB(51, 51, 153)
56 #333333 RGB(51, 51, 51)

RGB-коды можно использовать в VBA Excel наряду с индексами цветов стандартной палитры, а HEX-коды — в HTML.

Процент черного в оттенках серого

Процентное соотношение черного цвета в оттенках серого:

Индекс Наименование Процент черного Оттенок
1 Черный 100%
2 Белый 0%
15 Серебряный 25%
16 Серый 50%
48 Светло-серый 40%
56 Темный уголь 80%

Вывод 56-цветной палитры на лист

Вывод на рабочий лист Excel 56-цветной палитры с помощью кода VBA:

Источник

Содержание

  • Список кодов индекса цвета VBA
  • Свойство цвета VBA
  • Цвет VB
  • Цвета RGB
  • Список кодов ColorIndex и цвета RGB в Access VBA

При использовании VBA для кодирования Colorindex (или цвета фона) ячейки полезно знать, какое целое число будет равно какому цвету. Ниже приведено справочное изображение, на котором показан цвет и указан соответствующий ему Colorindex. он же Цветовая палитра VBA

Вот код, чтобы сделать его для себя или просто добавить эту страницу в закладки:

123456789101112131415 Sub ColorRef ()Dim x As IntegerДля x = от 1 до 56Если x <ТоCells (x, 1) .Interior.ColorIndex = xЯчейки (x, 2) = xЕщеЯчейки (x — 28, 3) .Interior.ColorIndex = xЯчейки (x — 28, 4) = xКонец, еслиДалее xКонец подписки

Примеры VBA ColorIndex

Установить цвет фона ячейки

1 Диапазон («A1»). Interior.ColorIndex = 6

Установить цвет шрифта ячейки

1 Диапазон («A1»). Font.ColorIndex = 5

Установить цвет границ ячеек

1 Диапазон («A1»). Borders.ColorIndex = 5

Получить индекс цвета фона ячейки

123 Dim col как целое числоcol = Range («A1»). Interior.ColorIndex

Установите цвет фона ячейки на цвет другой ячейки

1 Диапазон («A1»). Interior.ColorIndex = Range («B1»). Interior.ColorIndex

Свойство цвета VBA

Вместо использования свойства ColorIndex Excel / VBA вы можете использовать свойство Color. Свойство Color принимает два типа ввода:

  1. vbColor
  2. Цвета RGB

Мы обсудим это ниже:

Цвет VB

VB Color — самый простой способ установить цвета в VBA. Однако он также наименее гибкий. Чтобы установить цветовой код с помощью vbColor, используйте таблицу ниже:

Однако, как видно из таблицы, ваши возможности крайне ограничены.

Установить цвет фона ячейки

1 Диапазон («A1»). Interior.Color = vbYellow

Установить цвет шрифта ячейки

1 Диапазон («A1»). Font.Color = vbBlue

Установить цвет границ ячеек

1 Диапазон («A1»). Borders.Color = vbRed

Установите цвет фона ячейки на цвет другой ячейки

1 Диапазон («A1»). Interior.Color = Range («B1»). Interior.Color

Цвета RGB

RGB означает красный зеленый синий. Это три основных цвета, которые можно комбинировать для получения любого другого цвета. При вводе цветов как RGB введите значение от 0 до 255 для каждого цветового кода.

Вот пример:

1 Диапазон («A1»). Interior.Color = RGB (255,255,0)

Выше мы установили красный = 255 (максимальное значение), зеленый = 255 (максимальное значение) и синий = 0 (минимальное значение). Это устанавливает желтый цвет фона ячейки.

Вместо этого мы можем установить цвет шрифта ячейки на фиолетовый:

1 Диапазон («A1»). Interior.Color = RGB (128,0,128)

Существует множество онлайн-инструментов для поиска кода RGB для желаемого цвета (вот один).

Список кодов ColorIndex и цвета RGB в Access VBA

Access использует формы для отображения данных. Коды ColorIndex можно использовать для программного изменения цвета фона и цвета переднего плана объектов в формах Access.

12345 Частная подпрограмма cmdSave_Click ()’изменить цвет фона кнопки сохранения при сохранении записи.DoCmd.RunCommand acCmdSaveRecordcmdSave.BackColor = vbGreenКонец подписки

Вы поможете развитию сайта, поделившись страницей с друзьями

What is
Color Index Property?

The Excel VBA Color Index is used to change the color for
the cell or range of cells or text (located under the Font section). It sets
the color for Excel objects like cell color or shapes color. The Colo index
function also helps to fill the borders, cell background, and font colors.  It provides a unique identification for a
different type of colors.    

This function accepts 56 colors and 2 special colors (xlColorIndexAutomatic,
xlColorIndexNone) which are as follows:

  • 2 special color
Index Value Color Name Explanation
-4105 xlColorIndexAutomatic This method sets the default color of the index i.e., black.
-4142 xlColorIndexNone This method clears all the current index colors and set it
to none.
  • 56 Basic Colors

VBA Color Index Property

Syntax

  1. ColorIndex property of Excel VBA: This syntax
    is used for setting or returning the index color value for the specified Excel
    Objects.
Expression.ColorIndex
  • ColorIndex property to store or fetch Index
    value:
    This VBA Syntax to fetch the index color value for the excel sheet’s
    Font, Border, or Interior Color and store it another Variable:
dblColorValue= expression.ColorIndex
  • Set ColorIndex value to Excel Objects:
    This syntax enables the user to fill or modify the colors of Excel objects.
expression.ColorIndex= IndexValue (1 t0 56/ -4105/ -4142)
  • To set interior background: The
    following VBA syntax is used to fill the background color for the specified
    range of cells.
expression.Interior.ColorIndex= IndexValue (1 t0 56/ -4105/ -4142)
  • To set the border color: The
    following VBA syntax is used to fill the borders color for the Excel data.
expression.Borders.ColorIndex= IndexValue (1 t0 56/ -4105/ -4142)
  • To set the Font color: This syntax is
    used to fill the font colors.
expression.Font.ColorIndex= IndexValue (1 t0 56/ -4105/ -4142)

VBA code for ColorIndex Table

ColorIndex property 56 color shades. Let’s check all the
shades through the VBA code. Below is the code to run a code for printing the
Index colors in your Excel sheet:

Code:

Sub Colr_Indx_Table()
  Dim rCount As Byte, cCount As Byte
  Dim Colr_Indx As Byte
  Colr_Indx = 1
      'Row Counter 
      For rCount = 1 To 14
          'Column Counter
          For cCount = 1 To 4 
              'specifying the colors for the specified cell
              Cells(rCount, cCount).Interior.ColorIndex = Colr_Indx
              Colr_Indx = Colr_Indx + 1
              If Colr_Indx > 52 Then
              'Exiting out the loop
              GoTo jmp
              End If
          'Jumping to Next row 
          Next
      Next
 jmp:
  End Sub          

Output

Changing Font Color through VBA ColorIndex

Font options can be manually changed from the Home tab of
Excel Ribbon Toolbar. But you can even automate this task and select
appropriate Index colors using ColorIndex property of Font Object.

Example 1: To change the font color

Code:

Sub ColorIndex_FontColor()
     'Assigning Font color for the specified range to Index 32
     Range("A1:D14").Font.ColorIndex = 32
 End Sub 

VBA Color Index Property

Output

VBA Color Index Property

Example
2: To set default font color i.e., Black

We can set the default font color for the text by using
-4105 enumeration.

Code:

Sub ColorIndex_DeafultFontColor()
     'Assigning Font color for the specified range to default black color
     'by using -4105 enumeration
     Range ("A1:D14").Font.ColorIndex = -4105
 End Sub 

VBA Color Index Property

Output

VBA Color Index Property

Example
3:
Set Font Color to None

Excel font color can not be set to none. In the below
example, you will notice that the code has successfully run, but there is no
change in the font color. The ColorIndex -4142 does works with font objects.
Hence, there would be no effect.

Code:

Sub ColorIndex_NoneFontColor()
     'Assigning Font color for the specified range to -4142 enumeration
     Range("A1:D14").Font.ColorIndex = -4142
 End Sub 

VBA Color Index Property

Output

Before running the code

VBA Color Index Property

After running the code

VBA Color Index Property

 Background Color in VBA Excel

VBA
ColorIndex property also enables us to fill or modify the background (interior
of cell) color using the ColorIndex property of Interior object.

Example
1:
To set background color with Index color 52

Code:

Sub ColorIndex_BackgroundColor()
     'Assigning background color for the specified range to Index 52
     Range("A1:D14").Interior.ColorIndex = 52
 End Sub 

Output

VBA Color Index Property

Index Value Color Name Explanation
-4105 xlColorIndexAutomatic This method sets the default color of the index i.e.,
black.

Example
2: Default background color

The
ColorIndex property can also enable you to set the default color in the
background. For this, we can set the Interior.ColorIndex property to -4105
enumeration. It will eliminate the present BG color also remove the gridlines
for the specified range of cells.

Code:

Sub ColorIndex_DeaultBackgroundColor()
     'Clearing the background color for the specified cell
     Range("A1:D14").Interior.ColorIndex = -4105
 End Sub 

Output

VBA Color Index Property

Example 3: To set Background Index color to none

Many times, it required to clear the color formatting and
set the color to none. For this, we can set the Interior.ColorIndex property to
-4105 enumeration. It will automatically clear the background for the selected
range of cells.

Code:

Sub ColorIndex_ClearBckgroundColor()
     'Clearing the background color for the specified cell
     Range("A1:D14").Interior.ColorIndex = -4142
 End Sub 

Output

Before Running the code

VBA Color Index Property

After Running the code

VBA Color Index Property

Border
Color in Excel

ColorIndex property also enables you to change or alter the
colors for the borders. The ‘Borders’ object is used to set this property.

Example
1:
Setting the border color to Index 42

Code:

Sub ColorIndex_ChangingBorderColor()
     'changing the border color for the specified range to Index 42
     Range("A1:D14").Borders.ColorIndex = 42
 End Sub 

VBA Color Index Property

Output

VBA Color Index Property

Example 2: Using Default Border Color

The default border color, i.e., Black, can be achieved by
assigning the Borders.ColorIndex value to -4105 enumeration.

Code:

Sub ColorIndex_DefaultBorderColor()
     'Enabling the default border color by using Index -4105
     Range("A1:D14").Borders.ColorIndex = -4105
 End Sub 

VBA Color Index Property

Output

VBA Color Index Property

Example 3— Filling No Border color

We can clear the borders colors by assigning the
Borders.ColorIndex value to -4105 enumeration. Thus, the borders will no more
be visible.

Code:

Sub ColorIndex_FillNoBorderColor()
     'Filling no border color by using Index -4142 enumeration
     Range("A1:D14").Borders.ColorIndex = -4142
 End Sub 

Output

VBA Color Index Property

ColorIndex
Error Handling

The ColorIndex method can only take the predefined 56 index
values and 2 other enumerations ( -4105 enumeration, -4142 enumeration). If you
assign any other value apart from these, it will throw ‘Subscript out of Range’
error while running the code.

Code:

Sub ColorIndex_Error()
     'Assigning border color for the specified range to Index 142
     Range("A1:D14").Borders.ColorIndex = 142
 End Sub 

VBA Color Index Property

Output

VBA Color Index Property

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

ColorIndex property (Excel Graph)

vbagr10.chm5207225

vbagr10.chm5207225

excel

Excel.ColorIndex

e9a9c9de-8a42-0f61-be25-4c158709df68

04/10/2019

high

ColorIndex property (Excel Graph)

Returns or sets the color of the border, font, or interior, as shown in the following table. The color is specified as an index value into the current color palette, or as one of the following XlColorIndex constants: xlColorIndexAutomatic or xlColorIndexNone. Read/write Variant.

Syntax

expression.ColorIndex

expression Required. An expression that returns one of the objects in the Applies To list.

Remarks

Object Description
Border The color of the border.
Font The color of the font.
Interior The color of the interior fill. Set ColorIndex to xlColorIndexNone to specify that you don’t want an interior fill. Set ColorIndex to xlColorIndexAutomatic to specify the automatic fill (for drawing objects).

This property specifies a color as an index into the color palette. The following illustration shows the color-index values in the default color palette.

Color

Example

The following examples assume that you are using the default color palette.

This example sets the color of the major gridlines for the value axis.

With myChart.Axes(xlValue) 
 If .HasMajorGridlines Then 
 'Set color to blue 
 .MajorGridlines.Border.ColorIndex = 5 
 End If 
End With

This example sets the color of the chart area interior to red, and sets the border color to blue.

With myChart.ChartArea 
 .Interior.ColorIndex = 3 
 .Border.ColorIndex = 5 
End With

[!NOTE]
If you would like to use color with FormatCondition in Visual Basic, see the Interior.ColorIndex property.

[!includeSupport and feedback]

Colorindex in Excel VBA

Complete Excel VBA Course

Today let’s try to understand how ColorIndex property in Excel VBA works. It is an easy and effective way to quickly complete the development. ColorIndex property is normally used by VBA developers to fill cell, border and font colors. ColorIndex returns values from 1 to 56, -4105 and -4142.

Excel VBA Color Index: Color Variations

From index 1 to 56 are actual colors which provides various types of colors. Have a look at below color variations

Complete Excel VBA Course

ColorIndex in Excel VBA

Excel VBA Colorindex : Code

Let us now see how we can implement ColorIndex in VBA codes:

ColorIndex in Excel VBA

Code

Sub ColorIndexExample1()

    Sheet1.Range("C2").Interior.ColorIndex = 1 'Black
    Sheet1.Range("C3").Interior.ColorIndex = 3 'Red
    Sheet1.Range("C4").Interior.ColorIndex = 5 'Blue

End Sub

Explanation:

Here we have set the color of the cell using ColorIndex. ColorIndex = 1 is used to change the cell color to Black. Similarly, ColorIndex 2 and 3 are used to change the cell color to Red and Blue respectively. ”Example 2: Changing Border Color” 

Code:

Sub ColorIndexExample2()

    Sheet1.Range("C2").Borders.ColorIndex = 3 'Red
    Sheet1.Range("C3").Borders.ColorIndex = 4 'Green
    Sheet1.Range("C4").Borders.ColorIndex = 6 'Yellow

End Sub

Explanation:

In the above code, we have changed the border color of the cells using ColorIndex property available under Borders function of Range. ”Example 3: Changing Font Color” 

ColorIndex in Excel VBA

Code:

Sub ColorIndexExample3()

    Sheet1.Range("B2").Font.ColorIndex = 1 'Black
    Sheet1.Range("B3").Font.ColorIndex = 3 'Red
    Sheet1.Range("B4").Font.ColorIndex = 5 'Blue

End Sub

Explanation:

In this third example, we have changed font color of the cell using ColorIndex property.

Both -4105 and -4142 are special enumeration to set the ColorIndex to Automatic or None. If ColorIndex is supplied as -4105 (xlColorIndexAutomatic) then cell color, border or font is set to Automatic. Below is a sample code

ColorIndex in Excel VBA

Code:

Sub ColorIndexExample4()

    Sheet1.Range("C2").Interior.ColorIndex = xlColorIndexAutomatic

End Sub

Explanation:

The above code changes the cell color of C2 on Sheet1 to Automatic which is white here. Similarly, -4142 (xlColorIndexNone) is used to set ColorIndex to none. Below is a sample code of the same:

ColorIndex in Excel VBA

Code:

Sub ColorIndexExample5()

    Sheet1.Range("C3").Interior.ColorIndex = xlColorIndexNone

End Sub

Explanation:

The above code changes the cell color of C3 on Sheet1 to None.=”How to Get ColorIndex of a Cell?” Below is sample code to get the ColorIndex value of a Cell Color, Font or Border:

ColorIndex in Excel VBA

Code:

Sub ColorIndexExample6()

    Sheet1.Range("C2").Value = Sheet1.Range("B2").Interior.ColorIndex 'Cell ColorIndex
    Sheet1.Range("C3").Value = Sheet1.Range("B3").Font.ColorIndex 'Font ColorIndex
    Sheet1.Range("C4").Value = Sheet1.Range("B4").Borders.ColorIndex 'Border ColorIndex

End Sub

Explanation:

In the above code, we are reading the ColorIndex of Cell, Font, and Border Colors the value of the ColorIndex is then stored back in the sheet in the column.  You can also make use of few color Constants defined in Excel VBA for quick reference.

ColorIndex in Excel VBA

Code:

Sub ColorConstantsExample()

    Sheet1.Range("C2").Interior.Color = vbBlack
    Sheet1.Range("C3").Interior.Color = vbBlue
    Sheet1.Range("C4").Interior.Color = vbCyan
    Sheet1.Range("C5").Interior.Color = vbGreen
    Sheet1.Range("C6").Interior.Color = vbMagenta
    Sheet1.Range("C7").Interior.Color = vbRed
    Sheet1.Range("C8").Interior.Color = vbWhite
    Sheet1.Range("C9").Interior.Color = vbYellow

End Sub

There is also one more way to work with colors using RGB (Red Green Blue) function. The function requires 3 numbers from 0 to 255 [e.g. RGB(23,122,98)]. Have a look at below code:

ColorIndex in Excel VBA

Sub RGBExample()

    Sheet1.Range("B2").Interior.Color = RGB(255, 0, 0) 'Red
    Sheet1.Range("B3").Interior.Color = RGB(0, 255, 0) 'Green
    Sheet1.Range("B4").Interior.Color = RGB(0, 0, 255) 'Blue

End Sub

Explanation:

In the above code, we are using RGB VBA function to change the cell colors.

Download Practice File

You can also practice this through our practice files. Click on the below link to download the practice file.

Recommended Articles

  • VBA to read Excel data using a connection string
  • Excel VBA tool to get file properties
  • VBA Code to Re-link MS Access Link Tables
  • VBA Code to list files in folders
  • VBA Code to check if file Exists in Folder

Excel VBA Course : Beginners to Advanced

We are currently offering our Excel VBA Course at discounted prices. This course includes On Demand Videos, Practice Assignments, Q&A Support from our Experts. Also after successfully completion of the certification, will share the success with Certificate of Completion

This course is going to help you to excel your skills in Excel VBA with our real time case studies.

Lets get connected and start learning now. Click here to Enroll.

Secrets of Excel Data Visualization: Beginners to Advanced Course

Here is another best rated Excel Charts and Graph Course from excelsirji. This courses also includes On Demand Videos, Practice Assignments, Q&A Support from our Experts.

This Course will enable you to become Excel Data Visualization Expert as it consists many charts preparation method which you will not find over the internet.

So Enroll now to become expert in Excel Data Visualization. Click here to Enroll.

Понравилась статья? Поделить с друзьями:
  • Индексация формула расчета в excel
  • Индекс цен в excel
  • Индекс функция excel для чайников
  • Индекс формула в excel поискпоз примеры
  • Индекс формула excel с примерами