Interior color excel vba colors

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

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

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

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

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

Sub ColorTest1()

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

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

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

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

End Sub

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

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

Sub ColorTest11()

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

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

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

End Sub

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

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

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

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

Sub ColorTest2()

MsgBox Range(«A1»).Interior.Color

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

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

MsgBox Cells(3, 6).Interior.Color

End Sub

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

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

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

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

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

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

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

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

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

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

Палитра Excel

Палитра Excel

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

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

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

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

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

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

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

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

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

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

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

MsgBox Range(«A1»).Interior.ColorIndex

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

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

Sub ColorIndex()

Dim i As Byte

For i = 1 To 56

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

Next

End Sub

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

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


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. Свойство Interior.Color (Excel)
  2. Синтаксис
  3. Примечания
  4. Пример
  5. Поддержка и обратная связь
  6. Interior.Color property (Excel)
  7. Syntax
  8. Remarks
  9. Example
  10. Support and feedback
  11. Excel VBA: ColorIndex Codes List & RGB Colors
  12. VBA Color Index Codes List
  13. VBA ColorIndex Examples
  14. Set Cell Background Color
  15. Set Cell Font Color
  16. Set Cell Borders Color
  17. Get Cell Background ColorIndex
  18. Set a Cell Background Color to Another Cell’s Color
  19. VBA Color Property
  20. VB Color
  21. Set Cell Background Color
  22. Set Cell Font Color
  23. Set Cell Borders Color
  24. Set a Cell Background Color to Another Cell’s Color
  25. RGB Colors
  26. ColorIndex Codes List & RGB Colors in Access VBA
  27. VBA Code Examples Add-in
  28. Свойство ColorIndex (Excel Graph)
  29. Синтаксис
  30. Примечания
  31. Пример
  32. Поддержка и обратная связь
  33. ColorIndex property (Excel Graph)
  34. Syntax
  35. Remarks
  36. Example
  37. Support and feedback

Свойство Interior.Color (Excel)

Возвращает или задает основной цвет объекта, как показано в таблице в разделе примечаний. Используйте функцию RGB для создания значения цвета. Для чтения и записи, Variant.

Синтаксис

expression. Цвет

Выражение Выражение, возвращающее объект Interior .

Примечания

Object Цвет
Border Цвет границы.
Borders Цвет всех четырех границ диапазона. Если они не совпадают по цвету, функция Color возвращает значение 0 (ноль).
Font Цвет шрифта.
Interior Цвет заливки ячейки или цвет заливки объекта рисунка.
Вкладка Цвет вкладки.

Пример

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

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

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

Источник

Interior.Color property (Excel)

Returns or sets the primary color of the object, as shown in the table in the remarks section. Use the RGB function to create a color value. Read/write Variant.

Syntax

expression.Color

expression An expression that returns an Interior object.

Object Color
Border The color of the border.
Borders The color of all four borders of a range. If they’re not all the same color, Color returns 0 (zero).
Font The color of the font.
Interior The cell shading color or the drawing object fill color.
Tab The color of the tab.

Example

This example sets the color of the tick-mark labels on the value axis on Chart1.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

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.

Источник

Свойство 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 и обратная связь.

Источник

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.

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.

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.

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

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

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

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

Содержание

  1. Описание работы функции
  2. Пример использования
  3. Свойство .Interior.Color объекта Range
  4. Заливка ячейки цветом в VBA Excel
  5. Вывод сообщений о числовых значениях цветов
  6. Форматирование диапазона
  7. Нажатие кнопки Enter
  8. Вставка символа
  9. Добавление дополнительного символа
  10. Коды различных цветов в MS Excel 2003

Описание работы функции

Функция =ЦВЕТЗАЛИВКИ(ЯЧЕЙКА) возвращает код цвета заливки выбранной ячейки. Имеет один обязательный аргумент:

  • ЯЧЕЙКА – ссылка на ячейку, для которой необходимо применить функцию.

Ниже представлен пример, демонстрирующий работу функции.

Следует обратить внимание на тот факт, что функция не пересчитывается автоматически. Это связано с тем, что изменение цвета заливки ячейки Excel не приводит к пересчету формул. Для пересчета формулы необходимо пользоваться сочетанием клавиш Ctrl+Alt+F9

Пример использования

Так как заливка ячеек значительно упрощает восприятие данных, то пользоваться ей любят практически все пользователи. Однако есть и большой минус – в стандартном функционале Excel отсутствует возможность выполнять операции на основе цвета заливки. Нельзя просуммировать ячейки определенного цвета, посчитать их количество, найти максимальное и так далее.

С помощью функции ЦВЕТЗАЛИВКИ все это становится выполнимым. Например, “протяните” данную формулу с цветом заливки в соседнем столбце и производите вычисления на основе числового кода ячейки.

Свойство .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

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

Числовые значения цветов запомнить невозможно, поэтому часто возникает вопрос о том, как узнать числовое значение фона ячейки. Следующий код 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.

Форматирование диапазона

Самый известный способ поставить прочерк в ячейке – это присвоить ей текстовый формат. Правда, этот вариант не всегда помогает.

  1. Выделяем ячейку, в которую нужно поставить прочерк. Кликаем по ней правой кнопкой мыши. В появившемся контекстном меню выбираем пункт «Формат ячейки». Можно вместо этих действий нажать на клавиатуре сочетание клавиш Ctrl+1.
  2. Запускается окно форматирования. Переходим во вкладку «Число», если оно было открыто в другой вкладке. В блоке параметров «Числовые форматы» выделяем пункт «Текстовый». Жмем на кнопку «OK».

После этого выделенной ячейке будет присвоено свойство текстового формата. Все введенные в нее значения будут восприниматься не как объекты для вычислений, а как простой текст. Теперь в данную область можно вводить символ «-» с клавиатуры и он отобразится именно как прочерк, а не будет восприниматься программой, как знак «минус».

Существует ещё один вариант переформатирования ячейки в текстовый вид. Для этого, находясь во вкладке «Главная», нужно кликнуть по выпадающему списку форматов данных, который расположен на ленте в блоке инструментов «Число». Открывается перечень доступных видов форматирования. В этом списке нужно просто выбрать пункт «Текстовый».

Нажатие кнопки Enter

Но данный способ не во всех случаях работает. Зачастую, даже после проведения этой процедуры при вводе символа «-» вместо нужного пользователю знака появляются все те же ссылки на другие диапазоны. Кроме того, это не всегда удобно, особенно если в таблице ячейки с прочерками чередуются с ячейками, заполненными данными. Во-первых, в этом случае вам придется форматировать каждую из них в отдельности, во-вторых, у ячеек данной таблицы будет разный формат, что тоже не всегда приемлемо. Но можно сделать и по-другому.

  1. Выделяем ячейку, в которую нужно поставить прочерк. Жмем на кнопку «Выровнять по центру», которая находится на ленте во вкладке «Главная» в группе инструментов «Выравнивание». А также кликаем по кнопке «Выровнять по середине», находящейся в том же блоке. Это нужно для того, чтобы прочерк располагался именно по центру ячейки, как и должно быть, а не слева.
  2. Набираем в ячейке с клавиатуры символ «-». После этого не делаем никаких движений мышкой, а сразу жмем на кнопку Enter, чтобы перейти на следующую строку. Если вместо этого пользователь кликнет мышкой, то в ячейке, где должен стоять прочерк, опять появится формула.

Данный метод хорош своей простотой и тем, что работает при любом виде форматирования. Но, в то же время, используя его, нужно с осторожностью относиться к редактированию содержимого ячейки, так как из-за одного неправильного действия вместо прочерка может опять отобразиться формула.

Вставка символа

Ещё один вариант написания прочерка в Эксель – это вставка символа.

  1. Выделяем ячейку, куда нужно вставить прочерк. Переходим во вкладку «Вставка». На ленте в блоке инструментов «Символы» кликаем по кнопке «Символ».
  2. Находясь во вкладке «Символы», устанавливаем в окне поля «Набор» параметр «Символы рамок». В центральной части окна ищем знак «─» и выделяем его. Затем жмем на кнопку «Вставить».

После этого прочерк отразится в выделенной ячейке.

Существует и другой вариант действий в рамках данного способа. Находясь в окне «Символ», переходим во вкладку «Специальные знаки». В открывшемся списке выделяем пункт «Длинное тире». Жмем на кнопку «Вставить». Результат будет тот же, что и в предыдущем варианте.

Данный способ хорош тем, что не нужно будет опасаться сделанного неправильного движения мышкой. Символ все равно не изменится на формулу. Кроме того, визуально прочерк поставленный данным способом выглядит лучше, чем короткий символ, набранный с клавиатуры. Главный недостаток данного варианта – это потребность выполнить сразу несколько манипуляций, что влечет за собой временные потери.

Добавление дополнительного символа

Кроме того, существует ещё один способ поставить прочерк. Правда, визуально этот вариант не для всех пользователей будет приемлемым, так как предполагает наличие в ячейке, кроме собственно знака «-», ещё одного символа.

  1. Выделяем ячейку, в которой нужно установить прочерк, и ставим в ней с клавиатуры символ «‘». Он располагается на той же кнопке, что и буква «Э» в кириллической раскладке. Затем тут же без пробела устанавливаем символ «-».
  2. Жмем на кнопку Enter или выделяем курсором с помощью мыши любую другую ячейку. При использовании данного способа это не принципиально важно. Как видим, после этих действий на листе был установлен знак прочерка, а дополнительный символ «’» заметен лишь в строке формул при выделении ячейки.

Существует целый ряд способов установить в ячейку прочерк, выбор между которыми пользователь может сделать согласно целям использования конкретного документа. Большинство людей при первой неудачной попытке поставить нужный символ пытаются сменить формат ячеек. К сожалению, это далеко не всегда срабатывает. К счастью, существуют и другие варианты выполнения данной задачи: переход на другую строку с помощью кнопки Enter, использование символов через кнопку на ленте, применение дополнительного знака «’». Каждый из этих способов имеет свои достоинства и недостатки, которые были описаны выше. Универсального варианта, который бы максимально подходил для установки прочерка в Экселе во всех возможных ситуациях, не существует.

Коды различных цветов в MS Excel 2003

Коды различных цветов при использовании конструкции типа .Interior.ColorIndex. Бесцветный код: -4142

Источники

  • https://micro-solution.ru/projects/addin_vba-excel/color_interior
  • https://vremya-ne-zhdet.ru/vba-excel/tsvet-yacheyki-zalivka-fon/
  • http://word-office.ru/kak-sdelat-chtoby-vmesto-nulya-byl-procherk-v-excel.html
  • http://aqqew.blogspot.com/2011/03/ms-excel-2003.html

Excel VBA RGB Color

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

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

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

VBA-RGB

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

Below is the syntax of the RGB color function.

VBA RGB Syntax

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

Change Color of Cells using VBA RGB Function

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

Example #1

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

VBA RGB Example 1

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

Start the macro procedure first.

Code:

Sub RGB_Example1()

End Sub

VBA RGB Example 1.0

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

Code:

Sub RGB_Example1()

  Range ("A1:A8")

End Sub

Example 1.2

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

Code:

Sub RGB_Example1()

  Range("A1:A8").Font

End Sub

VBA RGB Example 1.3

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

Code:

Sub RGB_Example1()

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

End Sub

Example 1.4

Put an equal sign and open the RGB function.

Code:

Sub RGB_Example1()

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

End Sub

VBA RGB Example 1.5

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

Code:

Sub RGB_Example1()

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

End Sub

 Example 1.9

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

Output:

VBA RGB Example 1.7.0

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

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

Example 1.8

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

Example #2

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

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

Code:

Sub RGB_Example2()

  Range ("A1:A8").

End Sub

VBA RGB Example 2

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

Code:

Sub RGB_Example2()

  Range("A1:A8").Interior

End Sub

Example 2.1

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

Code:

Sub RGB_Example2()

  Range("A1:A8").Interior.

End Sub

VBA RGB Example 2.2

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

Code:

Sub RGB_Example2()

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

End Sub

Example 2.3

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

Code:

Sub RGB_Example2()

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

End Sub

VBA RGB Example 2.4

Enter the random number as you want.

Code:

Sub RGB_Example2()

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

End Sub

Example 2.6

Run the code and see the background color.

Output:

VBA RGB Example 2.5.0

The background color has changed.

Things to Remember Here

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

Recommended Articles

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

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

In this article, let’s look at the various ways to set or remove the interior/background color of a cell or range – ie to fill the cell.  We’ll also have a look at how to fill a cell/range with a pattern. Finally, we’ll review how to get the color input from the user using xlDialogEditColor and working with color gradients.

Example 1: Set the color of a cell / range

The .Interior.Color property is used to set the color of a cell or a range. There are various methods in which we can do this.

'Using XlRgbColor Enumeration - for few cells in a row
Range("B2:D2").Interior.Color = rgbDarkGreen

'Using Color Constants - for a cell using row and column number
Cells(3, 2).Interior.Color = vbYellow

'Specifying the RGB values - using A1 notation
Range("B4").Interior.Color = RGB(255, 0, 0)

'Using Color Code - for few cells in a column
Range("B5:B6").Interior.Color = 15773696

'Using Color Index - for a range
Range("B7:D8").Interior.ColorIndex = 7

This is how the output will look

For more details, refer to article Excel VBA, Cell Fill Color

Example 2: Set the color of a an entire row

You can use the .Interior.Color property on an entire row. Say you want to highlight all rows where the value of a column satisfies a condition:

Sub highlightRows()
    Dim rowNo As Integer
    For rowNo = 3 To 12
        If Sheet1.Cells(rowNo, 3).Value < 30 Then
            Rows(rowNo).Interior.Color = vbRed
        End If
    Next
End Sub

Here is the Excel before and after executing the code.

Example 3: Set the color of a an entire column

Similar to Example 2, you can fill an entire column using:

'Set color for column
Columns(2).Interior.Color = vbCyan

Example 4: Remove the color from a cell / range

You can also remove the background color of a cell by setting it to xlNone

'Remove color
Range("A1").Interior.Color = xlNone

or you can set a cell to have automatic color using xlColorIndexAutomatic

'Set color to automatic
Range("A1").Interior.ColorIndex = xlColorIndexAutomatic

Example 5: Get the color code of a cell

You can also get the color code of a cell. The line below gets the color code of the color used to fill cell A1 and prints it in cell B1:

'gets the color code used to fill cell A1
Cells(1, 2) = Range("A1").Interior.Color

Example 6: Get the color input from the user using xlDialogEditColor

The xlDialogEditColor is a dialog used to get a color code from the user. This dialog has 2 tabs: Standard and which we will see soon.

Syntax:

intResult = Application.Dialogs(xlDialogEditColor).Show(intIndex, [intRed], [intGreen], [intBlue])

intResult: Zero if the user cancels the dialog and -1 if the user selects a color.
intIndex: Selected color when the edit color dialog is opened. It is also used as an identifier to get the value of the color selected by the user. (More details below).
intRed, intGreen, intBlue: Red, blue and green components of a color

There are 2 methods for calling this dialog:

1. Displaying the standard tab: If only the intIndex is specified and the last 3 parameters are omitted, standard tab will be displayed. intIndex will decide the color index initially selected in the standard tab. This is a number between zero and 56.

intResult = Application.Dialogs(xlDialogEditColor).Show(20)

2. The custom tab is initially displayed. If all the 4 parameters, including the RGB values, are specified, the custom tab will be displayed.

 
intResult = Application.Dialogs(xlDialogEditColor).Show(20, 100, 100, 200) 

So, here is the complete code to get the color code from the user:

Sub changeColor()

Dim intResult As Long, intColor As Long

'displays the color dialog
intResult = Application.Dialogs(xlDialogEditColor).Show(40, 100, 100, 200)

'gets the color selected by the user
intColor = ThisWorkbook.Colors(40)

'changes the fill color of cell A1
Range("A1").Interior.Color = intColor

End Sub

Note: The intIndex specified in the xlDialogEditColor (40 in our example) is also the index used by ThisWorkbook.Colors. You need to make sure that these two numbers match.

Example 7: Gradient’s Colors

You can create a gradient using “xlPatternLinearGradient”

Range("A1").Interior.Pattern = xlPatternLinearGradient

It will look like this:

A gradient can have one or more colorStops, and each ColorStop has a position (a value between 0 and 1) and a color property. When you create a gradient, by default, the gradient has two ColorStop objects. One of the color stop objects has the position 1 and the other has the position 2. In order to be able to fully use the gradient properties in VBA, it is best to change the default positions to 0 and 1. In this way we would be able to have additional positions (colorStops) in between (i.e 0.5, 0.3). Let us now look at an example.

Sub multiColorStops()
Dim objColorStop As ColorStop
Dim lngColor1 As Long

'First create a gradient
Range("A1").Interior.Pattern = xlPatternLinearGradient

'Changes orientation to vertical (default is horizontal) - optional
Range("A1").Interior.Gradient.Degree = 90

'Clears all previous colorStop objects as they are at position 1 and 2
Range("A1").Interior.Gradient.ColorStops.Clear

'Start creating multiple colorStops at various positions from 0 to 1
Set objColorStop = Range("A1").Interior.Gradient.ColorStops.Add(0)

'Set the color for each colorstop
objColorStop.Color = vbYellow

Set objColorStop = Range("A1").Interior.Gradient.ColorStops.Add(0.33)
objColorStop.Color = vbRed

Set objColorStop = Range("A1").Interior.Gradient.ColorStops.Add(0.66)
objColorStop.Color = vbGreen

Set objColorStop = Range("A1").Interior.Gradient.ColorStops.Add(1)
objColorStop.Color = vbBlue

End Sub

The final result will look like this.

For more details, please refer to the article Excel VBA, Gradient’s Colors

Example 8: Color Patterns

Using VBA, you can also apply various patterns to cells in Excel. The patterns available can be seen in the snapshot below (Right click on a Cell > Format Cells > Fill tab > Pattern Style):

The pattern of a cell can be changed using the xlPattern enumeration. The code below changes the pattern of cell A1 to the checker pattern:

range("A1").Interior.Pattern = XlPattern.xlPatternChecker

Result:

You can also change the color of the pattern using the code below:

Range("A1").Interior.PatternColor = vbBlue

Result:

You can get a complete list of the XlPattern Enumeration in Excel here.

To get the index (as specified in the link above) of the pattern applied in a cell use:

MsgBox Range("A1").Interior.Pattern

It will display 9 for the checker pattern that we have applied earlier

For more details, refer to the article Excel VBA, Fill Pattern

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

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

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

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

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

enter image description here

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

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

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

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

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


StrLen = Len(Trim(text))


    If StrLen < Cnt Then

        For LP = 1 To Cnt - StrLen

            Padded = Padded & "0"

        Next LP

    End If

ZeroPad = Padded & Trim(text)

ENDOF:


End Function

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

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

Понравилась статья? Поделить с друзьями:
  • Invoice and template and word
  • Interface in microsoft excel
  • Inviting accepting refusing excel 9
  • Interesting word with definition
  • Invitation in word templates