Interior rgb excel color

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


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) & "&"

 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

#1

29.04.2015 12:39:26

Уважаемые форумчане, можно получить цвет заливки ячейки Excel таким образом:

Код
 Set R = Range("A1")
 x1 = R.Interior.Color 'в цифровом формате, например белый -"16777215"
 x2 = Hex$(x1) 'в шестнадцатеричном выражении - "FFFFFF" 
 x3 = "&H00" & x2 & "&" ' в формате H00+Hex - "&H00FFFFFF&" -используются в пользовательских формах Excel

Как получить в формате RGB (255,255,255), т.е. R=255, G=255, B=255?

Изменено: bedvit29.04.2015 12:45:13

«Бритва Оккама» или «Принцип Калашникова»?

 

Hugo

Пользователь

Сообщений: 23249
Регистрация: 22.12.2012

#2

29.04.2015 12:55:42

У себя в заметках нашёл такое (файл не качается…):

Код
Если необходимо вычислить RGB, то это делается так:
(фрагмент из файла Уокенбаха, пример здесь: http://www.planetaexcel.ru/docs/forum_upload/post_74452.xls)

Dim HexDigits As String
Dim BluePart As Integer, GreenPart As Integer, RedPart As Integer
UserForm1.SampleLabel.BackColor = ColorButton.BackColor
HexDigits = Hex(ColorButton.BackColor)
Do Until Len(HexDigits) = 6
HexDigits = "0" & HexDigits 'pad with zeros
Loop
BluePart = Val("&h" & Left(HexDigits, 2))
GreenPart = Val("&h" & Mid(HexDigits, 3, 2))
RedPart = Val("&h" & Right(HexDigits, 2))
UserForm1.RGBLabel.Caption = RedPart & " " & GreenPart & " " & BluePart

 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

#3

29.04.2015 14:06:53

Hugo, использовал Ваши данные, вышло следующее:

Код
...
Set R = Range("A1") 'вводим нужную ячейку
x1 = R.Interior.Color 'в цифровом формате, например белый -"16777215"
x2 = Hex$(x1) 'в шестнадцатеричном выражении - "FFFFFF"
Do Until Len(x2) = 6
x2 = "0" & x2 'догоняем 6 знаков нулями
DoEvents
Loop
x3 = "&H00" & x2 & "&" ' в формате H00+Hex - "&H00FFFFFF&" -используются в пользовательских формах Excel
R = Val("&h" & Right(x2, 2))
G = Val("&h" & Mid(x2, 3, 2))
B = Val("&h" & Left(x2, 2))
'Debug.Print R & " " & G & " " & B  'или MsgBox R & " " & G & " " & B    '-посмотреть... 
...

Спасибо!

Изменено: bedvit29.04.2015 14:10:22

«Бритва Оккама» или «Принцип Калашникова»?

 

Hugo

Пользователь

Сообщений: 23249
Регистрация: 22.12.2012

#4

29.04.2015 15:20:44

Не понял зачем там такое сложное

Код
Do Until Len(HexDigits) = 6
HexDigits = "0" & HexDigits 'pad with zeros
Loop

когда можно просто

Код
HexDigits = Right("000000" & HexDigits, 6)
 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

«Бритва Оккама» или «Принцип Калашникова»?

 

Слэн

Пользователь

Сообщений: 5192
Регистрация: 16.01.2013

#6

29.04.2015 16:05:07

так R.Interior.Color это запись rgb в виде (r+g*256+ b*256^2)

таким образом:

Код
Function rgb_(Rng)
Dim x, r, g, b
x = Rng.Interior.Color
b = Int(x / 65536)
x = x - b * 65536
g = Int(x / 256)
r = x - g * 256
rgb_ = "(" & r & "," & g & "," & b & ")"
End Function
Sub q()
ActiveCell.Interior.Color = rgb(125,128,200)
MsgBox rgb_(ActiveCell)
End Sub

Изменено: Слэн29.04.2015 16:07:08

Живи и дай жить..

 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

#7

29.04.2015 18:42:10

Слэн, отлично!
Hugo, Слэн, коллеги по Excel, кому интересна эта тема ))…
…набросал небольшую форму перевода из одной системы цветов в другую. (см. вложение)

Прикрепленные файлы

  • Цвет.xlsb (32.26 КБ)

Изменено: bedvit29.04.2015 18:45:42

«Бритва Оккама» или «Принцип Калашникова»?

Содержание

  1. Interior.Color property (Excel)
  2. Syntax
  3. Remarks
  4. Example
  5. Support and feedback
  6. Свойство Interior.Color (Excel)
  7. Синтаксис
  8. Примечания
  9. Пример
  10. Поддержка и обратная связь
  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. VBA Excel. Цвет ячейки
  29. Свойство .Interior.Color объекта Range
  30. Заливка ячейки цветом в VBA Excel
  31. Вывод сообщений о числовых значениях цветов
  32. Использование предопределенных констант
  33. Цветовая модель RGB
  34. Свойство .Interior.ColorIndex объекта Range
  35. VBA RGB
  36. Excel VBA RGB Color
  37. Change Color of Cells using VBA RGB Function
  38. Example #1
  39. Example #2
  40. Things to Remember Here
  41. Recommended Articles

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.

Источник

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

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

Синтаксис

expression. Цвет

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

Примечания

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

Пример

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

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

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

Источник

Excel VBA: ColorIndex Codes List & RGB Colors

In this Article

VBA Color Index Codes List

When using VBA to code the Colorindex (or background color) of a cell it is useful to know what integer will equal what color. Below is a reference picture which shows the color and lists it’s respective Colorindex. aka VBA Color Palette

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

VBA ColorIndex Examples

Set Cell Background Color

This example sets the cell’s background color.

Set Cell Font Color

This example sets the cell’s font color.

Set Cell Borders Color

This example sets the cell’s border color.

Get Cell Background ColorIndex

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

Set a Cell Background Color to Another Cell’s Color

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

VBA Color Property

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

We will discuss these below:

VB Color

VB Color is the easiest way to set colors in VBA. However, it’s also the least flexible. To set a color code using vbColor use the table below:

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

Set Cell Background Color

Set Cell Font Color

Set Cell Borders Color

Set a Cell Background Color to Another Cell’s Color

RGB Colors

RGB stands for Red Green Blue. These are the three primary colors that can be combined to produce any other color. When entering colors as RGB, enter a value between 0 and 255 for each color code.

Here’s an example:

Above we’ve set Red = 255 (max value), Green = 255 (max value), and Blue = 0 (min value). This sets the cell background color to Yellow.

Instead we can set the cell font color to purple:

There are numerous online tools to find the RGB code for your desired color (here’s one).

ColorIndex Codes List & RGB Colors in Access VBA

Access uses forms to display data. You can use the ColorIndex Codes to programmatically change the background color and foreground color of objects in your Access forms.

VBA Code Examples Add-in

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

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

Источник

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

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

Источник

What does VBA Excel RGB Property do?

VBA Excel RGB Property is a color Property of Objects, commonly used for Cell color or Shape color.

“RGB” stands for Red Green Blue, which are known as three additive primary colors, which can be combined to produce other colors. For example, purple is a mix of blue and red.  In RGB Property, you need to give a value (from 0 to 255) for each color in order to mix a new color. For example, Red = 255 means the brightness of color red is 100%.

rgb color

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

http://www.ifreesite.com/color/

http://big-coronasdklua.blogspot.hk/2011/04/rgb.html

You may also want to compare ColorIndex Property with RGB Property to use a different Property to set color for Cells.

Syntax of VBA Excel RGB Property

expression.RGB(red, green, blue)

red Integer from 0-255
green Integer from 0-255
blue Integer from 0-255

Example of Excel VBA RGB Property

Example 1: Set Cell A1 font color to red

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

Example 2: Set Cell A1 back color to red

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

Example 3: Set Cell A1 border color to red

Range("A1").Borders.Color = RGB(255, 0, 0)

Usually Property comes in a pair, one is to Set Property Method and another is  Get Property Method. However, RGB does not seem to have the Get Method.

To get the RGB Color, we need to get the use Interior.Color Property to get Interior Color first and then convert to RGB color based on the below formula

Interior Color = red+ green * 256 + blue * 256 ^ 2

Note carefully that if a Cell is colorless (no color), Interior.Color would return value 16777215, which is also the white color.

Below is a Function to get RGB color, where r, g, b are RGB value of Red, Green, Blue

Public Function wRGB(rng As Range)
 Dim intColor As Long
 Dim rgb As String
 intColor = rng.Interior.Color
 r = intColor And 255
 g = intColor  256 And 255
 b = intColor  256 ^ 2 And 255
 wRGB = r & "," & g & "," & b
End Function

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)

Содержание

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

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

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

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

Примеры VBA ColorIndex

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

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

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

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

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

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

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

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

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

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

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

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

  1. vbColor
  2. Цвета RGB

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

Цвет VB

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

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

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

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

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

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

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

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

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

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

Цвета RGB

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

Вот пример:

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

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

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

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

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

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

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

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

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

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

Понравилась статья? Поделить с друзьями:
  • Interior pattern vba excel
  • Invoice templates free word
  • Invoice templates for word
  • Interior design by one word
  • Invoice template free for excel