Colours in excel vba

Understanding Color Codes

Every color is identified by a unique number. For example, 255 represents Red. 16774980 represent a specific cyan.

You can also convert any decimal number to its Hexadecimal representation (or Hex for short). For example, that cyan color number equals FFF744 in Hex representation (use any decimal to hex converter you find on the web to see how it works).

You can assign the color codes to any Color property of any object in either their decimal or hex representation. Precede the Hex value with the &H prefix (our cyan code will be set to: &HFFF744). For example, the background color of cell A1 can be set to be cyan in one of the following two options:

Range("A1").Interior.Color = &HFFF744

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

Tip: to clear the background (Fill) color of a range, assign it the value -4142. Luckily, we have an Excel enumeration for that, so you do not need to remember the specific code, just assign xlNone like that:

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

The RGB representation of a color

Another way to represent a color is by its unique combination of the Red, Green and Blue components, or RGB in short. Each component takes a value between 1 and 255.

Our cyan color above has a mix of 68 red, 247 green and 255 blue.

VBA offers an RGB function to convert a mix of RGB values to the decimal code of a color, making it useful to assign an RGB mix to any Color property. Let’s set the font color of cell A1:

Range("A1").Font.Color = RGB(68,247,255)

You can use Excel to choose a color you like from the color selection dialog box to see its RGB values.

Working with Colors in Excel VBA

In recent Excel versions the Hex code of the color is also presented. If not, you can use any RGB to Hex converter (such as this one) to find the Hex code of a color.

The twist of Hex color codes in Excel

As you noticed, a hex color code contains 6 characters. That is a construction of two characters for the R (Red) code in the mix, two characters for the G (Green) and two characters for the B (Blue), resulting in the RGB mix that also uniquely identifies a color.

You may also know that colors in Webpages are also usually represented in their hex representation, preceded by the hash (“#”) symbol. You would expect that #FFF744 will show the cyan on a webpage. You would be surprised to see a bright yellow instead.

The reason is that while the Hex representation of a color is constructed by joining the RGB codes for the Web, Excel constructs its color codes by joining the BGR codes. Yep, the R and the B are swapped.

So, if you want to see our beautiful cyan on your Webpage, swap the first “FF” with the last “44” in our code, resulting to: #44F7FF.

By the way, you might want to remember that swapping trick when you set specific colors for different controls when you design your User Forms. This will be valid to represent our cyan code in any color property: &HFF3399.

Setting color codes as constants

Colors are a great candidate for constants, as in many cases their value doesn’t change that often, yet we still want a consistent and readable VBA code.

Constants can take any value, in both Hex and decimal. For example:

Public Const DATE_PICKER_BG_COLOR = &HFF3399

Tip: as constants cannot be assigned functions, RGB() cannot be used here. A quick way to find the numeric value of any RGB set would be using the Immediate Window in the VBA Editor (CTRL+G). To print out the numeric value of RGB(68,247,255), type in the following statement in the Immediate Window and press Enter: ?RGB(68,247,255)

Working with Colors in Excel VBA

Color codes enumerations

Excel VBA maintains enumerations for a bunch of popular colors. This means that you don’t have the know the color code of these colors, just use the enumeration label for the color you want.

For example, vbRed enumerates 255 (the color code for red). Print the value of vbGreen in the immediate Window, what do you get?

The enumerated colors are:

vbBlack, vbWhite, vbCyan, vbBlue, vbYellow, vbRed, vbMagenta, vbGreen.

Setting the font color of cell A1 to yellow, was never easier than:

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

Using the ColorIndex property

In addition to the Color property used to set the color of some Excel objects, you will also find the ColorIndex property for these objects.

The ColorIndex property is a legacy from way back versions of Excel, but still supported.

The idea here is a fixed collection of 56 colors, each assigned its own numeric index. See the table below:

Working with Colors in Excel VBA

If these 56 colors satisfy your eye, you can simply assign any of these index numbers to the ColorIndex property of an object to set (or read) its color, like that:

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

Hey, don’t forget to share this Blog post with others! Thanks!

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


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

Go to Top

Содержание

  1. Свойство ColorIndex (Excel Graph)
  2. Синтаксис
  3. Примечания
  4. Пример
  5. Поддержка и обратная связь
  6. VBA Excel. Стандартная палитра из 56 цветов
  7. Стандартная палитра из 56 цветов
  8. Наименования 56 цветов палитры
  9. RGB и HEX коды оттенков палитры
  10. Процент черного в оттенках серого
  11. Вывод 56-цветной палитры на лист
  12. Excel VBA color code list – ColorIndex, RGB color, VB color
  13. Excel ColorIndex
  14. Excel RGB color
  15. Excel VB color
  16. Excel VBA ColorIndex
  17. VBA Reference
  18. 120+ Project Management Templates
  19. Syntax of Excel VBA ColorIndex
  20. ColorIndex in Excel VBA
  21. VBA to Print ColorIndex Table
  22. Set ColorIndex in Excel VBA
  23. Font Colors in Excel VBA
  24. Interior Colors in Excel VBA
  25. Border Colors in Excel VBA
  26. Clear Colors in Excel VBA
  27. Clear Background Color in Excel VBA
  28. VBA Colors
  29. Excel VBA Color Constants
  30. RGB Colors in Excel VBA

Свойство 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. Стандартная палитра из 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:

Источник

Excel VBA color code list – ColorIndex, RGB color, VB color

This Excel tutorial collects the VBA color code list for reference purpose, which includes ColorIndex, RGB color, VB color.

Excel ColorIndex

VBA Excel ColorIndex Property is to set color or get color for Objects like Cell color and Shape color. ColorIndex offers 56 basic colors plus the following special numbers.

ColorIndex Value Explanation
-4142 / xlColorIndexNone / xlNone No fill
-4105 / xlColorIndexAutomatic / xlAutomatic Default color (white)

Example 1: Set Cell A1 font color to red

Example 2: Set Cell A1 back color to red

Example 3: Set Cell A1 border color to red

Example 4: Get Cell A1 ColorIndex

Excel RGB color

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 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%.

If you try to change a color but you don’t know the color code, you can visit the websites below

Example 1: Set Cell A1 font color to red

Example 2: Set Cell A1 back color to red

Example 3: Set Cell A1 border color to red

Excel VB color

The simplest way to apply color is using the VB color name, you don’t have to remember which number represents which color, the the color for your choice is very limited.

Источник

Excel VBA ColorIndex

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:

50+ Excel Templates

50+ PowerPoint Templates

25+ Word 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
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

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.

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.

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

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.

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.

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

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.

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

Border Colors in Excel VBA

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

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.

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:

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

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:

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.

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

Источник

This Excel tutorial collects the VBA color code list for reference purpose, which includes ColorIndex, RGB color, VB color.

VBA Excel ColorIndex Property is to set color or get color for Objects like Cell color and Shape color. ColorIndex offers 56 basic colors plus the following special numbers.

ColorIndex Value Explanation
-4142 / xlColorIndexNone / xlNone No fill
-4105 / xlColorIndexAutomatic / xlAutomatic Default color (white)

colorindex_10

Example 1: Set Cell A1 font color to red

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

Example 2: Set Cell A1 back color to red

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

Example 3: Set Cell A1 border color to red

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

Example 4: Get Cell A1 ColorIndex

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

Excel RGB color

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 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

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)

Excel VB color

The simplest way to apply color is using the VB color name, you don’t have to remember which number represents which color, the the color for your choice is very limited.

excel_vbcolor_10

Example: Set Cell A1 font color to red

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

ThreeWave
Color Functions In Excel

This page describes VBA functions you can use to work with colors on worksheets.
ShortFadeBar

Excel provides essentially no support in worksheet functions for working with cell colors. However, colors are
often used in spreadsheets to indicate some sort of value or category. Thus comes the need for functions that
can work with colors on the worksheet. This page describes a number of functions for VBA that can be called from
worksheet cells or other VBA procedures.

Like everything else in computers, a color is really just a number. Any color that can be displayed on the computer
screen is defined in terms of three primary components: a red component, a green component, and a blue component.
Collectively, these are known as RGB values. The RGB color model is called an «additive»
model because other, non-primary colors, such as violet, are created by combining the red, green, and blue primary
colors in varying degrees. Violet, for example, is roughly a half-intensity red plus a half-intesity blue.
Each primary color component is stored as a number between 0 and 255 (or, in hex, &H00 to
&HFF). A color is a 4 byte number of the format 00BBGGRR, where
RR, GG, and BB values are the Red, Green,
and Blue values, each of which is between 0 and 255 (&HFF). If all component values are 0,
the RGB color is 0, which is black. If all component values are 255 (&HFF),
the RGB color is 16,777,215 (&H00 FFFFFF), or white. All other colors combinations of
values for the red, green, and blue components. The VBA RGB function can be used to combine
red, green, and blue values to a single RGB color value.

USAGE NOTE: This page will use the terms background, fill, and interior interchangably to
refer to the background of a cell. The proper term is the Interior Property of a
Range object.

It is worth drawing attention to the component values in an Long RGB value. The left-to-right order of colors as stored
in an RGB value is Blue, Green, Red. This is the opposite of the letters in the name RGB. Keep this in mind when
using hex literals to specify a color. (Fortunately, the order of parameters to the RGB function
is Red, Green, Blue.)

Excel supports colors for fonts and background fills through what is called the Color palette. The palette is an array or
series of 56 RGB colors. The value of each of those 56 colors may be any of the 16 million available colors, but the
palette, and thus the number of distinct colors in a workbook, is limited to 56 colors. The RGB values in the palette are accessed by
the ColorIndex property of a Font object (for the font color) or the
Interior object (for the background color). The ColorIndex is an
offset or index into the palette and thus has a value betweeen 1 and 56. In the default, unmodified palette, the 3rd
element in the palette is the RGB value 255 (&HFF), which is red.

When you format a cell’s background to red, for example, you are actually assigning to the ColorIndex
property of the Interior a value of 3. Excel reads the 3 in the ColorIndex
property, goes to the 3rd element of the palette to get the actual RGB color. If you modify the palette, say by changing the 3rd
element from red (255 = &HFF) to blue (16,711,680 = &HFF0000), all items
that were once red are now blue. This is because the ColorIndex property remains equal to 3, but
value of the 3rd element in the palette was changed from red to blue.

You change the values in the default palette by modifying the Colors array of the Workbook
object. For example, to change the color referenced by ColorIndex value 3 to blue, use

    Workbooks("SomeBook.xls").Colors(3) = RGB(0,0,255)

In addition to the 56 colors in the palette, there are two special values used with colors, which we will encounter later.
These are xlColorIndexNone, which specifies that no color has been assigned, and
xlColorIndexAutomatic, which specifies that a system default color (typically black)
should be used.

NOTE: These functions work only with Excel’s 56 color pallet. They do not
support theme colors or colors not in the 56 color pallet, or colors that are
the result of Conditional Formatting..

You can use some very simple code to display the current settings of the color palette. The following code will
change the color of the first 56 cells in the active worksheet to the palette colors. The row number is the same as
the color index number. So, cell A3, which is in row 3, will be the color assigned to color index 3.

    Sub Displaypalette()
        Dim N As Long
        For N = 1 To 56
            Cells(N, 1).Interior.ColorIndex = N
        Next N
    End Sub

If you have modified as workbook’s palette by using Workbook.Colors, you can reset the palette back to
the default values with Workbooks(«SomeBook.xls»).ResetColors.

SectionBreak

This discussion of colors, the Color palette, and the ColorIndex property leads us to the
fundamental Function of most of the code described on this page. The ColorIndexOfOneCell
function returns the color index of either the background or the font of a cell. The procedure declaration is
shown below.

    Function ColorIndexOfOneCell(Cell As Range, OfText As Boolean, _
                                 DefaultColorIndex As Long) As Long
download You can download a module file that contains all the code
on this page. The various procedures within the modColorFunctions.bas module
call upon one another, so you should import the entire module into your project, rather than copying single
procedures.

Here, Cell is the cell whose color is to be read. OfText is either
True or False indicating whether to return the color index of the Font (OfText = True) or the
background (OfText = False). The
DefaultColorIndex parameter is a color index value (1 to 56) that is to be returned if no
specific color has been assigned to the Font (xlColorIndexAutomatic) or the background fill
(xlColorIndexNone). If you set OfText to True, you should most likely set
DefaultColorIndex to 1 (black). If you set OfText to False, you should set
DefaultColorIndex to 2 (white). For example, if range A1 has a background fill
equal to red (ColorIndex = 3), the code:

Dim Result As Long
Result = ColorIndexOfOneCell(Cell:=Range("A1"), OfText:=False, DefaultColorIndex:=1)

will return 3. This can be called directly from a worksheet cell with a formula like:

=COLORINDEXOFONECELL(A1,FALSE,1)

The complete ColorIndexOfOneCell function follows:

    Function ColorIndexOfOneCell(Cell As Range, OfText As Boolean, _
        DefaultColorIndex As Long) As Long
    
    Dim CI As Long
    
    Application.Volatile True
    If OfText = True Then
        CI = Cell(1, 1).Font.ColorIndex
    Else
        CI = Cell(1, 1).Interior.ColorIndex
    End If
    If CI < 0 Then
        If IsValidColorIndex(ColorIndex:=DefaultColorIndex) = True Then
            CI = DefaultColorIndex
        Else
            CI = -1
        End If
    End If
    
    ColorIndexOfOneCell = CI
    
    End Function
    Private Function IsValidColorIndex(ColorIndex As Long) As Boolean 
        Select Case ColorIndex 
            Case 1 To 56 
                IsValidColorIndex = True 
            Case xlColorIndexAutomatic, xlColorIndexNone  
                IsValidColorIndex = True 
            Case Else 
                IsValidColorIndex = False 
        End Select 
    End Function 

By itself, the ColorIndexOfOneCell function is of limited utility. However, it is used by another
function, ColorIndexOfRange, which returns an array of color index values for a range of cells. The
declaration for this function is shown below:

    Function ColorIndexOfRange(InRange As Range, _
                   Optional OfText As Boolean = False, _
                   Optional DefaultColorIndex As Long = -1) As Variant

Here, InRange is the range whose color values are to be returned. OfText
is either True or False indicating whether to examine the color index of the Font (OfText = True)
or the background fill (OfText = False or omitted) of the cells in
InRange. The DefaultColorIndex value specifies
a color index to be returned if the actual color index value is either xlColorIndexNone or
xlColorIndexAutomatic. This function returns as its result an array of color index values (1
to 56) of each cell in InRange.

You can call ColorIndexOfRange as an array formula from a
range of cells to return the color indexs of another range of cells. For example, if you array-enter

=ColorIndexOfRange(A1:A10,FALSE,1)

into cells B1:B10, B1:B10 will list the color indexes of the
cells in A1:A10.

The complete code for ColorIndexOfRange is shown below:

    Function ColorIndexOfRange(InRange As Range, _
        Optional OfText As Boolean = False, _
        Optional DefaultColorIndex As Long = -1) As Variant
    
    
    Dim Arr() As Long
    Dim NumRows As Long
    Dim NumCols As Long
    Dim RowNdx As Long
    Dim ColNdx As Long
    Dim CI As Long
    Dim Trans As Boolean
    
    Application.Volatile True
    If InRange Is Nothing Then
        ColorIndexOfRange = CVErr(xlErrRef)
        Exit Function
    End If
    If InRange.Areas.Count > 1 Then
        ColorIndexOfRange = CVErr(xlErrRef)
        Exit Function
    End If
    If (DefaultColorIndex < -1) Or (DefaultColorIndex > 56) Then
        ColorIndexOfRange = CVErr(xlErrValue)
        Exit Function
    End If
    
    NumRows = InRange.Rows.Count
    NumCols = InRange.Columns.Count
    
    If (NumRows > 1) And (NumCols > 1) Then
        ReDim Arr(1 To NumRows, 1 To NumCols)
        For RowNdx = 1 To NumRows
            For ColNdx = 1 To NumCols
                CI = ColorIndexOfOneCell(Cell:=InRange(RowNdx, ColNdx), _
                    OfText:=OfText, DefaultColorIndex:=DefaultColorIndex)
                Arr(RowNdx, ColNdx) = CI
            Next ColNdx
        Next RowNdx
        Trans = False
    ElseIf NumRows > 1 Then
        ReDim Arr(1 To NumRows)
        For RowNdx = 1 To NumRows
            CI = ColorIndexOfOneCell(Cell:=InRange.Cells(RowNdx, 1), _
                OfText:=OfText, DefaultColorIndex:=DefaultColorIndex)
            Arr(RowNdx) = CI
        Next RowNdx
        Trans = True
    Else
        ReDim Arr(1 To NumCols)
        For ColNdx = 1 To NumCols
            CI = ColorIndexOfOneCell(Cell:=InRange.Cells(1, ColNdx), _
                OfText:=OfText, DefaultColorIndex:=DefaultColorIndex)
            Arr(ColNdx) = CI
        Next ColNdx
        Trans = False
    End If

    If IsObject(Application.Caller) = False Then
        Trans = False
    End If
    
    If Trans = False Then
        ColorIndexOfRange = Arr
    Else
        ColorIndexOfRange = Application.Transpose(Arr)
    End If
    
    End Function

You can use the ColorIndexOfRange function in other code, as:

    Sub AAA()
        Dim V As Variant
        Dim N As Long
        Dim RR As Range
        Set RR = Range("ColorCells")
        V = ColorIndexOfRange(InRange:=RR, OfText:=False, DefaultColorIndex:=1)
        If IsError(V) = True Then
            Debug.Print "*** ERROR: " & CStr(V)
            Exit Sub
        End If
        If IsArray(V) = True Then
            For N = LBound(V) To UBound(V)
                Debug.Print RR(N).Address, V(N)
            Next N
        End If
    End Sub

SectionBreak

Excel normally calculates the formula in a cell when a cell upon which that formula depends changes. For example, the formula
=SUM(A1:A10) is recalculated when any cell in A1:A10 is changed. However,
Excel does not consider changing a cell’s color to be significant to calculation, and therefore will not necessarily
recalculate a formula when a cell color is changed. Later on this page, we will see a function named CountColor
that counts the number of cells in a range that have a specific color index. If you change the color of a cell in the range
that is passed to CountColor, Excel will not recalculate the CountColor
function and, therefore, the result of CountColor may not agree with the actual colors on the
worksheet until a recalculation occurs. The relevant functions use Application.Volatile True to
force them to be recalculated when any calculation is done, but this is still insufficient. Simply changing
a cell color does not cause a calculation, so the function is not recalculated, even with Application.Volatile True

SectionBreak

While Excel provides no event for changing a cell’s color, you can use the Worksheet_Change event to
detect whether the user is entering ColorCells range and whether the user is exiting the
ColorCells range.

    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
        Static OldCell As Excel.Range
        If OldCell Is Nothing Then
            Set OldCell = ActiveCell
        End If
        
        If Not Application.Intersect(Target(1, 1), Range("ColorCells")) Is Nothing Then
            Me.Calculate
        
        ElseIf Application.Intersect(Target(1, 1), Range("ColorCells")) Is Nothing Then
            If Not Application.Intersect(OldCell, Range("ColorCells")) Is Nothing Then
                Me.Calculate
            End If
        End If
        Set OldCell = Target(1, 1)
    End Sub

This code tests whether the user has changed the selection from one cell in ColorCells to
another cell within ColorCells, and recalculates the worksheet. The code also test whether
the user moves the selecion from a cell within ColorCells to a cell outside
ColorCells. If this is true, the worksheet is calculated. Until Microsoft upgrades its
event system, this code is a close as you can get. It does calculate at the moment that the color is change, but
it does calculate as soon as the user selects a cell within ColorCells or exits the
ColorCells range.

SectionBreak

The ability to return an array of color indexes allows us to test the color indexes of ranges of cells and perform
operations based on comparisons of those values to a specific color index value. For example, we can use the
ColorIndexOfRange function in a formula to count the number of cells whose fill color is
red.

=SUMPRODUCT(--(COLORINDEXOFRANGE(B11:B17,FALSE,1)=3))

This function returns the number of cells in the range B11:B17 whose color index is 3, or red.
Rather than hard-coding the 3 in the formula, you can get the color index of another
cell with the ColorIndexOfOneCell function and pass that value to the
ColorIndexOfRange function. For example, to count the cells in B11:B17
that have a color index equal to the color index of cell H7, you would use the formula:

=SUMPRODUCT(--(COLORINDEXOFRANGE(B11:B17,FALSE,1)=COLORINDEXOFONECELL(H7,FALSE,1)))

For counting colors, the modColorFunctions
downloadable module provides a direct function named CountColor that counts the number of
cells in a range that have a color index (of either the Font or Interior
object) equal to a specified value.

information A NOTE ABOUT THE VBA CODE MODULE: The modColorFunctions downloadable module contains approximately 20 color-related
functions. These function call upon one another, so you should Import the entire module into your VBA Project rather than pasting in only
individual functions. If you don’t import the entire module, you may get errors reporting undefined function names.

The CountColor function is shown below:

Function CountColor(InRange As Range, ColorIndex As Long, _
    Optional OfText As Boolean = False) As Long


Dim R As Range
Dim N As Long
Dim CI As Long

If ColorIndex = 0 Then
    If OfText = False Then
        CI = xlColorIndexNone
    Else
        CI = xlColorIndexAutomatic
    End If
Else
    CI = ColorIndex
End If


Application.Volatile True
Select Case ColorIndex
    Case 0, xlColorIndexNone, xlColorIndexAutomatic
        ' OK
    Case Else
        If IsValidColorIndex(ColorIndex) = False Then
            CountColor = 0
            Exit Function
        End If
End Select

For Each R In InRange.Cells
    If OfText = True Then
        If R.Font.ColorIndex = CI Then
            N = N + 1
        End If
    Else
        If R.Interior.ColorIndex = CI Then
            N = N + 1
        End If
    End If
Next R

CountColor = N

End Function

You can call the CountColor function in a worksheet formula like the one shown below. This
will count the number of red cells in the range A1:A10.

=COUNTCOLOR(A1:A10,3,FALSE)

We can use the ColorIndexOfRange function to get the sum of the values in those cells whose
color index is some specified value. For example, the following array formula will sum
the values of the cells in range B11:B17 whose fill color is red.

=SUM(B11:B17*(COLORINDEXOFRANGE(B11:B17,FALSE,1)=3))

Like counting colors, summing values based on a color is a common task and the modColorFunctions
module provides a function for doing this directly. The SumColor function is shown below:

Function SumColor(TestRange As Range, SumRange As Range, _
    ColorIndex As Long, Optional OfText As Boolean = False) As Variant

Dim D As Double
Dim N As Long
Dim CI As Long

Application.Volatile True
If (TestRange.Areas.Count > 1) Or _
    (SumRange.Areas.Count > 1) Or _
    (TestRange.Rows.Count <> SumRange.Rows.Count) Or _
    (TestRange.Columns.Count <> SumRange.Columns.Count) Then
    SumColor = CVErr(xlErrRef)
    Exit Function
End If
    
If ColorIndex = 0 Then
    If OfText = False Then
        CI = xlColorIndexNone
    Else
        CI = xlColorIndexAutomatic
    End If
Else
    CI = ColorIndex
End If

Select Case CI
    Case 0, xlColorIndexAutomatic, xlColorIndexNone
        ' ok
    Case Else
        If IsValidColorIndex(ColorIndex:=ColorIndex) = False Then
            SumColor = CVErr(xlErrValue)
            Exit Function
        End If
End Select

For N = 1 To TestRange.Cells.Count
    With TestRange.Cells(N)
    If OfText = True Then
        If .Font.ColorIndex = CI Then
            If IsNumeric(SumRange.Cells(N).Value) = True Then
                D = D + SumRange.Cells(N).Value
            End If
        End If
    Else
        If .Interior.ColorIndex = CI Then
            If IsNumeric(SumRange.Cells(N).Value) = True Then
                D = D + SumRange.Cells(N).Value
            End If
        End If
    End If
    End With
Next N
            
SumColor = D

End Function
information In both the CountColor and SumColor functions,
you can specify a ColorIndex property value of 0 to indicate background Interiors
or Fonts that have no color assigned to them. Using 0 will work properly regardless of the value of the
OfText parameter. This is simpler than having to remember the numeric values
of xlColorIndexNone and xlColorIndexAutomatic.
The 0 works for testing either background Interior colors or Font colors.

The SumColor function is a color-based analog of both the SUM and
SUMIF function. It allows you to specify separate ranges for the range whose color indexes
are to be examined and the range of cells whose values are to be summed. If these two ranges are the same, the function
sums the cells whose color matches the specified value. For example, the following formula sums the values in
B11:B17 whose fill color is red.

=SUMCOLOR(B11:B17,B11:B17,3,FALSE)

In this formula, the range B11:B17 is both the range to test and the range to sum. These ranges
may be different. For example, the following formula examines the color index of the cells in B11:B17
and if that cell’s color index is 3, it sums the corresponding value from D11:D17.

=SUMCOLOR(B11:B17,D11:D17,3,FALSE)

Because the ColorIndexOfRange function returns an array of values, it can be used in any
array formula. For example, the following formula will return the minimum value whose fill color is red from the range B11:B17:

=MIN(IF(COLORINDEXOFRANGE(B11:B17,FALSE,1)=3,B11:B17,FALSE))

SectionBreak

The downloadable module contains a function named RangeOfColor that
will return a Range object consisting of the cells in an input range that have a font or fill color index equal to the specified
color index. The function declaration is:

    Function RangeOfColor(TestRange As Range, _
        ColorIndex As Long, Optional OfText As Boolean = False) As Range

You can use this function to get a range of cells with a red fill color. For example,

    Sub AAA()
        Dim R As Range
        Dim RR As Range
        Set RR = RangeOfColor(TestRange:=Range("A1:F20"), _
                ColorIndex:=3, OfText:=False)
        If Not RR Is Nothing Then
            For Each R In RR
                Debug.Print R.Address
            Next R
        Else
            Debug.Print "*** NO CELLS FOUND"
        End If
    End Sub

This will print to the VBA Immediate window the address of those cells in the range A1:F20 that
have a red fill color.

SectionBreak

The modColorFunctions module contains functions related to the Color palette and color
names.

DefaultColorpalette
This function returns an array that is the Excel default color palette. This array does not reflect changes that
have been made to Workbook.Colors. If the Option Base value
of the module that contains the DefaultColorpalette function (not the module from
which it is called) is Option Base 0, the result array has 57 elements (0 to 56) and element 0
has a value of -1. If the Option Base value is Option Base 1, the
result array has 56 elements (1 to 56). In either case, you can use a valid ColorIndex value
to return the RGB color value:

    Dim N As Long
    N = 3
    Debug.Print N, Hex(DefaultColorpalette(N))

DefaultColorNames
This function returns an array of the US English names of the colors in the default palette (not the palette as
modified with Workbook.Colors. These are the color names that appear in the Tool Tip Text elements
of Excel’s color commandbar dropdown. If the Option Base value
of the module that contains the DefaultColorNames function (not the module from
which it is called) is Option Base 0, the result array has 57 elements (0 to 56) and element 0
has a value of UNNAMED. If the Option Base value is Option Base 1, the
result array has 56 elements (1 to 56). In either case, you can use a valid ColorIndex value
to return the name of the color. Not all color have names — those that do not are represented in the array as the string
UNNAMED.

    Dim N As Long
    N = 3
    Debug.Print N, DefaultColorNames(N)

ColorNameOfRGB
This returns the US English color name corresponding to the specified RGB color if that color exists in the application
default palette. If the color is not found in the palette, the function returns vbNullString.

SectionBreak

The modColorFunctions module contains a number of functions for working with
RGB colors and color index values.

ColorIndexOfRGBLong
This returns the Color Index value of the specified RGB Long color value, if it exists in the current palette. Otherwise, it
returns 0.

IsColorpaletteDefault
This returns True if the palette associated with the specified workbook is the application default palette. This returns False
if the palette has been modified with Workbook.Colors.

IsColorIndexDefault
This returns True if the color associated with the specified color index is the same as the application default color index
value. This tells you if the color associated with a color index value has been changed.

RGBComponentsFromRGBLongToVariables
This splits an RGB Long value into the constituent red, green, and blue values, which are returned to the caller in the
ByRef variables. The function’s result is True if the input value was a valid RGB color or False if the input value was
not a valid RGB color. For example,

    Dim RGBColor As Long
    Dim Red As Long
    Dim Green As Long
    Dim Blue As Long
    Dim B As Boolean
    
    RGBColor = ActiveCell.Interior.Color
    B = RGBComponentsFromRGBLongToVariables(RGBColor, Red, Green, Blue)
    If B = True Then
        Debug.Print "Red: " & Red, "Green: " & Green, "Blue: " & Blue
    Else
        Debug.Print "Invalid value in RGBColor"
    End If

RGBComponentsFromRGBLong
This splits an RGB Long color value into the red, green, and blue components and returns them as an array of Longs.

    Arr(1) = Red
    Arr(2) = Green
    Arr(3) = Blue

SectionBreak

The modColorFunctions module contains a function named ChooseColorDialog
that will display a Windows Color Picker dialog and return the RGB Long color value. If the user cancels the dialog,
the result is -1. For example,

    Dim RGBColor As Long
    Dim Default As Long
    Default = RGB(255, 0, 255) 'default to purple
    RGBColor = ChooseColorDialog(DefaultColor:=Default)
    If RGBColor < 0 Then
        Debug.Print "*** USER CANCELLED"
    Else
        Debug.Print "Choice: " & Hex(RGBColor)
    End If

SectionBreak

In this section, we will use a VBA function to return the ColorIndex value of the color in the palette that
is closest to a given RGB Long color value. The entire concept of a «closest» color is somewhat subjective. Two people need not agree
whether one color is in fact closer to some color than another color. The method used here considers every RGB color to be a spatial
location in a 3-dimensional space where the axes are Red, Green, and Blue components of an RGB Long value. The code finds the
ColorIndex of the color that is the least distance in this space between a Colors(ColorIndex) value
and the RGB Long value to test. The distance is determined by the simple Pythagorean distance, but for speed of calculation
we omit the square root from the calculation.

Function ClosestColor(RGBLong As Long) As Long


Dim MinDist As Double    
Dim MinCI As Double      
Dim CI As Long           
Dim DistCI As Double     


 
Dim RedTest As Long
Dim GreenTest As Long
Dim BlueTest As Long

 
Dim RedCI As Long
Dim GreenCI As Long
Dim BlueCI As Long

 
If IsValidRGBLong(RGBLong) = False Then
    ClosestColor = 0
    Exit Function
End If

 
MinDist = 195075 ' 255^2 + 255^2 + 255^2. omit the square root.

 
RGBComponentsFromRGBLongToVariables RGBLong, RedTest, GreenTest, BlueTest

For CI = 1 To 56
    RGBComponentsFromRGBLongToVariables ThisWorkbook.Colors(CI), RedCI, GreenCI, BlueCI
     
    DistCI = ((RedTest - RedCI) ^ 2 + (GreenTest - GreenCI) ^ 2 + (BlueTest - BlueCI) ^ 2)
    If DistCI < MinDist Then
         
        MinDist = DistCI
        MinCI = CI
    End If
Next CI

ClosestColor = MinCI

End Function

This page last updated: 6-November-2008

Понравилась статья? Поделить с друзьями:
  • Colours in excel have changed
  • Colours in excel formulas
  • Colouring table in word
  • Colouring background in word
  • Coloured pages in word