Excel vba color all cells

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

In this article I will explain how you can set and get the fill color of cells using VBA. There are many times you may need to set the background colors of certain cells based upon a condition. Using conditional formatting is not always feasible as the formula may get very complex.

There are multiple ways to specify the color that you wish to use. Let us look at some examples

For more information about using colors in VBA for excel please see VBA Excel Colors.

Jump To:

  • Set
  • Get


Set:

The code below changes the fill color of cell “A1” to red:

'Using XlRgbColor Enumeration
Range("B2").Interior.Color = rgbDarkGreen
'Using Color Constants
Range("B3").Interior.Color = vbGreen
'Specifying the RGB values
Range("B4").Interior.Color = RGB(255, 0, 0)
'Using Color Code
Range("B5").Interior.Color = 15773696
'Using Color Index
Range("B6").Interior.ColorIndex = 6
'You can also specify no color or automatic color using
Range("B7").Interior.ColorIndex = xlNone
Range("B8").Interior.ColorIndex = xlColorIndexAutomatic

This is how the Excel will look before and after running the code.  Before:

before vba fill code

After:

vba fill code after

For more information about color constants please see Excel VBA ColorConstants.

For a complete example on setting the background color of cells based on color codes please see Excel VBA Color Code.


Get:

The line below gets the color code of the color used to fill cell A1 and prints it in cell B1:

Cells(1, 2) = Range("A1").Interior.Color

The following line of code does the same:

Cells(1, 2) = Range(Cells(1, 1), Cells(1, 1)).Interior.Color

Result:

Excel VBA, Color Code
For an example on getting the fill color used in a cell or range please see Excel VBA, Get Color Code.

Example:

Let us look at a more practical example of changing the background color of cells. Say, in your Excel program, you have an option to change the color theme of a sheet (or part of a sheet). So, you have 2 color themes, black and blue and a button for each. This is how it looks before:

vba color change example

You will use the code below to – check the background color of each cell in the table. If it is black, change it to blue and vice-versa.

Private Sub SetBlack_Click()
    Dim forecastTable As Range
    
    Set forecastTable = Range("B7:K17")
    For Each cell In forecastable
	   'Check the color of the cell	
        If cell.Interior.color = 9851952 Then
		  'If it is blue, change it to black
            cell.Interior.color = 0
        End If
    Next cell
End Sub

Private Sub SetBlue_Click()
    Dim forecastTable As Range
    
    Set forecastTable = Range("B7:K17")
    For Each cell In forecastTable
	   'Check the color of the cell	
        If cell.Interior.color = 0 Then
		  'If it is black, change it to blue
            cell.Interior.color = 9851952
        End If
    Next cell
    
End Sub

This is how the Excel will look after clicking on Blue Theme:

vba color change fill example blue

Instead of checking the color of each cell, you can also directly specify the range for which you want to change the color. This example was used to demonstrate how to change the color of all cells from one value to another

See also:

  • Excel VBA, Get Color Code
  • Excel VBA Color Code
  • VBA Excel Colors
  • Excel VBA, Formatting Cells and Ranges using the Macro Recorder
  • Excel VBA, Fill Pattern

If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website www.software-solutions-online.com

Содержание

  1. VBA Excel. Цвет ячейки
  2. Свойство .Interior.Color объекта Range
  3. Заливка ячейки цветом в VBA Excel
  4. Вывод сообщений о числовых значениях цветов
  5. Использование предопределенных констант
  6. Цветовая модель RGB
  7. Свойство .Interior.ColorIndex объекта Range
  8. VBA RGB
  9. Excel VBA RGB Color
  10. Change Color of Cells using VBA RGB Function
  11. Example #1
  12. Example #2
  13. Things to Remember Here
  14. Recommended Articles
  15. Change Background Color of Cell Range in Excel VBA
  16. VBA Reference
  17. 120+ Project Management Templates
  18. Description:
  19. Change Background Color of Cell Range in Excel VBA – Solution(s):
  20. Change Background Color of Cell Range in Excel VBA – Examples
  21. Change Background Color of Cell Range in Excel VBA – Download: Example File
  22. VBA Excel. Цвет ячейки (заливка, фон)
  23. Свойство .Interior.Color объекта Range
  24. Заливка ячейки цветом в VBA Excel
  25. Вывод сообщений о числовых значениях цветов
  26. Использование предопределенных констант
  27. Цветовая модель RGB
  28. Очистка ячейки (диапазона) от заливки
  29. Свойство .Interior.ColorIndex объекта Range
  30. 86 комментариев для “VBA Excel. Цвет ячейки (заливка, фон)”

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Источник

VBA RGB

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

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

Below is the syntax of the RGB color function.

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

Example #1

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

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:

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:

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:

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:

Put an equal sign and open the RGB function.

Code:

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

Code:

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

Output:

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.

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:

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:

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

Code:

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

Code:

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

Code:

Enter the random number as you want.

Code:

Run the code and see the background color.

Output:

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

Источник

Change Background Color of Cell Range 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:

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

Description:

It is an interesting feature in excel, we can change background color of Cell, Range in Excel VBA. Specially, while preparing reports or dashboards, we change the backgrounds to make it clean and get the professional look to our projects.

Change Background Color of Cell Range in Excel VBA – Solution(s):


We can use Interior.Color OR Interior.ColorIndex properties of a Rage/Cell to change the background colors.

Change Background Color of Cell Range in Excel VBA – Examples

The following examples will show you how to change the background or interior color in Excel using VBA.

Example 1

In this Example below I am changing the Range B3 Background Color using Cell Object

Example 2

In this Example below I am changing the Range B3 Background Color using Range Object

Example 3

We can also use RGB color format, instead of ColorIndex. See the following example:

Example 4

The following example will apply all the colorIndex form 1 to 55 in Activesheet.

Instructions:
  1. Open an excel workbook
  2. Press Alt+F11 to open VBA Editor
  3. Insert a new module from Insert menu
  4. Copy the above code and Paste in the code window
  5. Save the file as macro enabled workbook
  6. Press F5 to execute the procedure
  7. You can see the interior colors are changing as per our code

Change Background Color of Cell Range in Excel VBA – Download: Example File

Here is the sample screen-shot of the example file.

Download the file and explore how to change the interior or background colors in Excel using VBA.

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.

Источник

VBA Excel. Цвет ячейки (заливка, фон)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

86 комментариев для “VBA Excel. Цвет ячейки (заливка, фон)”

Спасибо, наконец то разобрался во всех перипетиях заливки и цвета шрифта.

Пожалуйста, Виктор. Очень рад, что статья пригодилась.

как проверить наличие фона?

Привет, Надежда!
Фон у ячейки есть всегда, по умолчанию — белый. Отсутствие цветного фона можно определить, проверив, является ли цвет ячейки белым:

Подскажите пожалуйста, как можно посчитать количество залитых определенным цветом ячеек в таблице?

Привет, Иван!
Посчитать ячейки с одинаковым фоном можно с помощью цикла.
Для реализации этого примера сначала выбираем в таблице ячейку с нужным цветом заливки. Затем запускаем код, который определяет цветовой индекс фона активной ячейки, диапазон таблицы вокруг нее и общее количество ячеек с такой заливкой в таблице.

Каким образом можно использовать не в процедуре, а именно в пользовательской функции VBA свойство .Interior.Color?
Скажем, проверять функцией значение какой-то ячейки и подкрашивать ячейку в зависимости от этого.

Фарин, пользовательская функция VBA предназначена только для возврата вычисленного значения в ячейку, в которой она расположена. Она не позволяет внутри себя менять формат своей ячейки, а также значения и форматы других ячеек.

Однако, с помощью пользовательской функции VBA можно вывести значения свойств ячейки, в которой она размещена:

В сети есть эксперименты по изменению значений других ячеек из пользовательской функции VBA, но они могут работать нестабильно и приводить к ошибкам.

Для подкрашивания ячейки в зависимости от ее значения используйте процедуру Sub или штатный инструмент Excel – условное форматирование.

а как можно закрасить только пустые ячейки ?

Лев, закрасить пустые ячейки можно с помощью цикла For Each… Next:

Евгений, спасибо за ссылку на интересный прием.

Евгений, день добрый.
Подскажите пожалуйста, как назначить ячейке цвет через значение RGB, которое в ней записано. Или цвет другой ячейки.

Привет, Александр!
Используйте функцию InStr, чтобы найти положение разделителей, а дальше функции Left и Mid. Смотрите пример с пробелом в качестве разделителя:

Или еще проще с помощью функции Split:

Добрый день!
подскажите, пожалуйста, как можно выводить из таблицы (150 столбцов х 150 строк) адрес ячеек (списком), если они имеют заливку определенного цвета.
Заранее спасибо!

Привет, Валентина!
Используйте два цикла For…Next. Определить числовой код цвета можно с помощью выделения одной из ячеек с нужным цветом.

столбец «D» имеет разноцветную заливку
надо справа от зеленой ячейки написать «Да»

Каким-то образом надо узнать числовое значение цвета, если он не стандартный — vbGreen. Например, можно выделить ячейку с нужным цветом и записать числовое значение цвета в переменную:

Евгений, спасибо за подсказку.
Все получилось

добрый день! подскажите, пожалуйста, как сделать, чтобы результаты выводились на отдельный лист ?
заранее спасибо!

Валентина, замените в коде имя «Лист2» на имя своего листа.

Евгений. Долгое время мучаюсь реализацией следующего сценария: в таблице Excel, которая является базой данных пациентов отделения есть столбец «G» в котором лаборанты отмечают исследования выполненные с контрастом «(С+)» и без «(C-)» и далее в столбце «N» они отмечаются количество использованного контраста «от 50мл до 200мл»; для удобства ввода и уменьшения числа непреднамеренных ошибок в столбцах реализована функция проверки данных что бы сотрудники могли выбирать уже готовые значения из списка и если ошибутся то выскочит ошибка; тем не менее сотрудники умудряются при заполнении таблицы не вносить количество использованного контраста. Вопрос заключается в том, как подкрасить ячейку для ввода количества контраста красным цветом при условии, что в ячейке столбца G фигурирует (С+) с целью акцентировать на этом внимание.
Заранее спасибо за ответ.

Добрый день, Алексей!
Примените условное форматирование:

1 Выберите столбец «N».
2 На вкладке ленты «Главная» перейдите по ссылкам «Условное форматирование» «Создать правило».
3 В открывшемся окне выберите тип правила: «Использовать формулу для определения форматируемых ячеек».
4 В строку формул вставьте =И(ЕСЛИ(G1=»(C+)»;1);ЕСЛИ(N1=»»;1)) . Буква «C» должна быть из одной раскладки (ENG или РУС) в формуле и в ячейке.
5 Нажмите кнопку «Формат» и на вкладке «Заливка» выберите красный цвет.
6 Закройте все окна, нажимая «OK».

Если в ячейке столбца «G» будет выбрано «(С+)», то ячейка той же строки в столбце «N» подкрасится красным цветом. После ввода значения в ячейку столбца «N», ее цвет изменится на первоначальный.

Спасибо Евгений! Ваш пример многое прояснил (в т.ч надо читать Уокенбаха и не филонить). Мне удалось заставить работать этот сценарий не так изящно как у Вас т.е создал для каждой отдельной переменной свое правило: пр. для ГМ. (С+) —> =ЕСЛИ(И(G5066=»ГМ. (С+)»;N5066=»»);»Истина»;»Ложь»)
МТ. (С+) —> =ЕСЛИ(И(G5066=»МТ. (С+)»;N5066=»»);»Истина»;»Ложь») и т.д всего 8 правил для каждого конкретного случая.
И применил их всех для столбца N:N

Ячейку G взял произвольно и в дальнейшем вообще убрал ее на лист метаданных (диапазоны переменных типа ГМ. (С+), МТ. (С+)…)
Еще раз благодарю за помощь! а есть возможность тоже самое сделать цикличным скриптом VBA ? (или я сморозил…).
Заранее спасибо за ответ.

Источник

VBA Code To Change Cell Color

Complete Excel VBA Course

Excel supports more than 16 million colors in a cell; hence you should know how to set the exact color in a cell. To do this, you can use RGB (Red, Green, Blue) function in VBA to set the color of a cell. The function requires 3 numbers from 0 to 255 [e.g. RGB(234,232,98)]. Below is a practice code that changes cell colors to Green, Red and Blue.

Change a Cells Background Color

VBA Code to Change Cell Color

'This function can be used to change the color of a
cell
Public Sub ChangeCellColor()
    '
    'Change cell color to green
    Sheet1.Range("C4").Interior.Color = RGB(0, 255, 0)
    '
    'Change cell color to red
    Sheet1.Range("C5").Interior.Color = RGB(255, 0, 0)
    '
    'Change cell color to blue
    Sheet1.Range("C6").Interior.Color = RGB(0, 0, 255)
    '
End Sub

VBA Code To Change Cell Color ,follow below steps:

Open an Excel file

  • Press Alt+F11
  • Insert a Module (Insert>Module) from menu bar
  • Paste the code in the module
  • Now add a shape in Excel sheet
  • Give a name to the shape like ‘Change Cell Color’
  • Right click on the shape and select ‘Assign Macro…’

VBA Code to change cell color

  • Select ‘ChangeCellColor’ from the list and click on ‘Ok’ button

  • Done, click on the shape to change the cell colors

Download Practice File

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

Recommended Articles

  • VBA to Read Excel Data using Connection String
  • Excel VBA Tool to Get File Properties
  • VBA Code to Re-link MS Access Link Tables
  • VBA Code to List Files in Folder
  • VBA Code to Check if File Exist in Folder

Excel VBA Course : Beginners to Advanced

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

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

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

Secrets of Excel Data Visualization: Beginners to Advanced Course

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

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

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

Понравилась статья? Поделить с друзьями:
  • Excel vba cell style
  • Excel vba collection dictionary
  • Excel vba cell size
  • Excel vba collapse all
  • Excel vba cell numberformat