Vba to color cells in excel

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

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

Синтаксис

выражение. ColorIndex

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

Примечания

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

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

Пример

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

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

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

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

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

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

Источник

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Источник

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.

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.

Источник

Читайте также:  Как настроить сканирование с принтера на компьютер kyocera 2540dn
Блог о рисовании и уроках фотошопа
Adblock
detector