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


As part of a VBA program, I have to set the background colors of certain cells to green, yellow or red, based on their values (basically a health monitor where green is okay, yellow is borderline and red is dangerous).

I know how to set the values of those cells, but how do I set the background color.

asked Dec 13, 2008 at 11:39

paxdiablo's user avatar

paxdiablopaxdiablo

844k233 gold badges1565 silver badges1937 bronze badges

You can use either:

ActiveCell.Interior.ColorIndex = 28

or

ActiveCell.Interior.Color = RGB(255,0,0)

answered Dec 13, 2008 at 11:43

Vinko Vrsalovic's user avatar

Vinko VrsalovicVinko Vrsalovic

328k53 gold badges332 silver badges370 bronze badges

2

This is a perfect example of where you should use the macro recorder. Turn on the recorder and set the color of the cells through the UI. Stop the recorder and review the macro. It will generate a bunch of extraneous code, but it will also show you syntax that works for what you are trying to accomplish. Strip out what you don’t need and modify (if you need to) what’s left.

answered Apr 18, 2012 at 2:34

Jon Crowell's user avatar

Jon CrowellJon Crowell

21.5k14 gold badges88 silver badges110 bronze badges

Do a quick ‘record macro’ to see the color number associated with the color you’re looking for (yellow highlight is 65535). Then erase the code and put

Sub Name()
Selection.Interior.Color = 65535 '(your number may be different depending on the above)
End Sub

answered Mar 4, 2020 at 15:07

Matt G's user avatar

1

or alternatively you could not bother coding for it and use the ‘conditional formatting’ function in Excel which will set the background colour and font colour based on cell value.

There are only two variables here so set the default to yellow and then overwrite when the value is greater than or less than your threshold values.

answered Dec 30, 2008 at 12:34

It doesn’t work if you use Function, but works if you Sub. However, you cannot call a sub from a cell using formula.

answered Mar 22, 2015 at 18:08

user4700453's user avatar

0

Changing background colors in Excel VBA is easy. Use the Interior property to return an Interior object. Then use the ColorIndex property of the Interior object to set the background color of a cell.

Place three command buttons on your worksheet and add the following code lines:

1. The code line below sets the background color of cell A1 to light blue.

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

Result:

Background Color in Excel VBA

2. The following code line sets the background color of cell A1 to ‘No Fill’.

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

Result:

No Fill

3. If you want to know the ColorIndex number of a color, simply ask Excel VBA.

MsgBox Selection.Interior.ColorIndex

Select cell A1 and click the command button on the sheet:

Get ColorIndex Number

Result:

ColorIndex Number

4. The ColorIndex property gives access to a color palette of 56 colors.

Color Palette

Note: download the Excel file to see how we created this color palette.

5. If you can’t find the specific color you are looking for, use the Color property and the RGB function.

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

Explanation: RGB stands for Red, Green and Blue. These are the three primary colors. Each component can take on a value from 0 to 255. With this function you can make every color. RGB(255,0,0) gives the pure Red color (ColorIndex = 3 produces the exact same result).

Skip to content

Change Background Color of Cell Range in Excel VBA

Home » Excel VBA » Change Background Color of Cell Range in Excel VBA

  • Change background colur- excel vba

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

Delete Worksheet in Excel VBA
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

Sub sbRangeFillColorExample1()

'Using Cell Object
Cells(3, 2).Interior.ColorIndex = 5 ' 5 indicates Blue Color

End Sub
Example 2

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

Sub sbRangeFillColorExample2()

'Using Range Object
Range("B3").Interior.ColorIndex = 5

End Sub
Example 3

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

Sub sbRangeFillColorExample3()
'Using Cell Object
Cells(3, 2).Interior.Color = RGB(0, 0, 250)

'Using Range Object
Range("B3").Interior.Color = RGB(0, 0, 250)

End Sub
Example 4

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

Sub sbPrintColorIndexColors()
Dim iCntr

For iCntr = 1 To 56
    Cells(iCntr, 1).Interior.ColorIndex = iCntr
    Cells(iCntr, 1) = iCntr
Next iCntr

End Sub
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.

Change Background Color of Cell Range in Excel VBA

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

ANALYSIS TABS – ColorIndex

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

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:

3 Comments

  1. Harbinder Singh
    April 13, 2017 at 12:23 PM — Reply

    need help in excel

    In company there are 10000 employee and all having duty in A shift, B shift, C shift. Each shift of 08 hrs

    i have to find those employee who work continuous 10 days or more then 10 days

    please help me to find the solution using VB macro in excel or any other way to find from huge no of data in excel

    Kindly provide me the solution.

  2. RandomOne
    May 23, 2017 at 5:46 AM — Reply

    Harbinder Singh
    its dependes of your database, can check with a vba code for filter based on the criteria, select the range and then color it,
    Regards!

  3. Ken Schleede
    July 10, 2019 at 6:44 AM — Reply

    Thanks! This is excellent. It allows me to control the colors much more reliably than conditional formatting.

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

Return to VBA Code Examples

This tutorial will demonstrate how to change a cell’s background color using VBA.

Change Cell Background Color with Interior.colorindex

To change a cell’s background color using VBA you can use the Interior.Colorindex property. Here’s a couple ways to change the background color of cell A1.

An example using the Range() method:

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

An example using the Cells() method:

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

Need an easy way to determine what number equals what color? Check out Color Reference For Colorindex.

vba-free-addin

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.

(No installation required!)

Free Download

Change the Background Colors in Excel VBA is an easy task.

In this blog post, you will learn about changing the background colors in Excel VBA.

In Excel, we change the background color by selecting the range, then go to the ‘Home’ tab then go to the ‘Font’ group and select the ‘Fill Color’ option.

Click the drop-down link and there are multiple colors, which you can apply into your selected range where you want to change the background color.

Here, you will learn about how to change the background colors with the help of VBA.

In VBA, you will learn to change the background color with three (3) easiest methods.

In this method, you can use 8 standard colors in the VBA. These color are as follows:-

Black – vbBlack
White – vbWhite
Red -vbRed
Blue – vbBlue
Green – vbGreen
Yellow – vbYellow
Cyan – vbCyan
Magenta – vbMagenta

8 Standard Colors

These are 8 standard colors, which we can apply with their names in VBA.

Change the Background Colors in Excel VBA, we need to use the above standard colors in VBA Code.

Now, we will apply these codes in one of our VBA macros to change the colors of background colors in Excel VBA within cells from range “A1” to “A10”.

Sub Standard_Color()

Range(“A1:A10”).Interior.Color = vbBlack
Range(“A1:A10”).Interior.Color = vbWhite
Range(“A1:A10”).Interior.Color = vbRed
Range(“A1:A10”).Interior.Color = vbBlue
Range(“A1:A10”).Interior.Color = vbGreen
Range(“A1:A10”).Interior.Color = vbYellow
Range(“A1:A10”).Interior.Color = vbCyan
Range(“A1:A10”).Interior.Color = vbMagenta
End Sub

VBA Code To Change Background Color

By executing the above VBA code by pressing “F8” step by step, our result will be shown as the below image:-

Change the Background Colors in Excel VBA
Change Background Color Image – 01

If you execute the above code by pressing “F8”, you will notice each execution will change the background colors.

Below is the another method to “Change the Background Colors in Excel VBA”.

Change the Background ColorsUsing ColorIndex Method

In this method, there are 56 colors that we can apply to ‘change our background colors in Excel VBA,.

Each number from 1 to 56 has a particular color code.

When we will apply this method to change the background color, we will change the code ‘ColorIndex’ in place of ‘Color’.

Now we will apply for these numbers in the VBA editor window to change the background colors.

See the code in the VBA editor window:-

Sub ColorIndex_Method()

Range(“A1:A10”).Interior.ColorIndex = 1
Range(“A1:A10”).Interior.ColorIndex = 2
Range(“A1:A10”).Interior.ColorIndex = 5
Range(“A1:A10”).Interior.ColorIndex = 15
Range(“A1:A10”).Interior.ColorIndex = 25
Range(“A1:A10”).Interior.ColorIndex = 45
Range(“A1:A10”).Interior.ColorIndex = 55
Range(“A1:A10”).Interior.ColorIndex = 56

End Sub

Color Index Method to Change the Background Color

Now we will execute the above code by pressing “F8” again and again to execute each of the codes.

See below image for result:-

Change the Background Colors in Excel VBA
Color Index Method to Change the background colors
Color Index Method to Change the Background

Here we have only applied some code to change the background colors in Excel VBA.

But, in this method, we can use the number from 1 to 56 to apply different colors.

Changing background color by RGB (Red, Green, Blue) Method

RGB is a short form of Red, Green, and Blue.

These are the basic or primary colors and by combining these colors we can create multiple other new colors.

This is our 3rd method to ‘change the background colors in Excel VBA.

When applying these colors in VBA can be written as RGB (255,255,255).

Values in the bracket are the color code of each color, where the range of each color from 0 to 255. Where “0” is the minimum and “255” is the maximum range.

We can create multiples of colors with the help of these three (3) color codes.

Between ranges we can put any number for any color combination.

See the VBA code in the VBA Editor window:-

Sub Background_RGB_Method()

Range(“A1:A10”).Interior.Color = RGB(0, 0, 0)
‘for Black Color
Range(“A1:A10”).Interior.Color = RGB(0, 0, 255)
‘for Blue Color
Range(“A1:A10”).Interior.Color = RGB(0, 255, 0)
‘ For green Color
Range(“A1:A10”).Interior.Color = RGB(0, 255, 255)
‘For Cyan Color
Range(“A1:A10”).Interior.Color = RGB(255, 0, 0)
‘For Red Color
Range(“A1:A10”).Interior.Color = RGB(255, 0, 255)
‘For Magenta Color
Range(“A1:A10”).Interior.Color = RGB(255, 255, 0)
‘For Yellow Color

End Sub

Using RGB method to Change Background Color

Now pressing “F8” to execute the above code step by step, we will get the following result.

See the image below:-

Change the Background Colors in Excel VBA
RGB Method to Change the Background Color

Here, you can see that how we change the background colors in Excel VBA by the RGB method.

Here, in this post, we have explained the 3 easiest methods to change the background colors in Excel VBA.

Furthermore, details for the Excel Interior Color (Background Color) are provided on the Microsoft Office website.

I hope you find this post useful.

Please feel free to put your comments or suggestion.

Thanks

Related Post

Copy and Paste in Excel VBA: 4 Easiest Way

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

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)

<<Lesson 15>> [Contents] <<Lesson 17>>

In this Lesson, we will explore how to write Excel VBA code that formats the color of an MS Excel spreadsheet. Using  Excel VBA code, we can change the font color as well as the background color of each cell effortlessly.

Alright, let’s create a program that can format random font and background colors using a randomizing process. Colors can be assigned using a number of methods in Excel VBA, but it is easier to use the RGB function. The RGB function has three numbers corresponding to the red, green and blue components. The range of values of the three numbers is from 0 to 255. A mixture of the three primary colors will produce different colors.

The syntax to set the font color is

cells(i,j).Font.Color=RGB(x,y,x)

where x,y, z are any numbers between 1 and 255

The syntax to set the cell’s background color is

cells(i,j).Interior.Color=RGB(x,y,x)

Where x,y, z can be any number between 1 and 255

Some RGB Color Codes are shown in the following chart,

Color RGB Code
(0,0,0)
(255,0,0)
(255,255,0)
(255,165,0)
(0,0,255)
(0,128,0)
(128,0,128)

Example 16.1

In this example, clicking the command button changes the background colors from Cells(1,1) to Cells(7,1) according to the specified RGB color codes. It also format the font colors from Cells(1,2) to cells(7,2) using specified RGB color codes.

The code

Private Sub CommandButton1_Click()
Dim i As Integer

‘To fill the cells with colors using RGB codes
Cells(1, 1).Interior.Color = RGB(0, 0, 0)
Cells(2, 1).Interior.Color = RGB(255, 0, 0)
Cells(3, 1).Interior.Color = RGB(255, 255, 0)
Cells(4, 1).Interior.Color = RGB(255, 165, 0)
Cells(5, 1).Interior.Color = RGB(0, 0, 255)
Cells(6, 1).Interior.Color = RGB(0, 128, 0)
Cells(7, 1).Interior.Color = RGB(128, 0, 128)
‘To format font color with RGB codes
For i = 1 To 7
Cells(i, 2).Value = “Font Color”
Next
Cells(1, 2).Font.Color = RGB(0, 0, 0)
Cells(2, 2).Font.Color = RGB(255, 0, 0)
Cells(3, 2).Font.Color = RGB(255, 255, 0)
Cells(4, 2).Font.Color = RGB(255, 165, 0)
Cells(5, 2).Font.Color = RGB(0, 0, 255)
Cells(6, 2).Font.Color = RGB(0, 128, 0)
Cells(7, 2).Font.Color = RGB(128, 0, 128)

End Sub

Excel VBA

Example 16.2

In this example, the font color in cells(1,1) and background color in cells(2,1) are changing for every click of the command button due to the randomized process.Rnd is a random number between 0 and 1, therefore 255* Rnd will produce a number between 0 and 255  and Int(255*Rnd) will produce integers that take the values from 0 to 254
So we need to add 1 to get random integers from 0 to 255.
For example;Rnd=0.229
255*Rnd=58.395
Int(58.395)=58

The code

Private Sub CommandButton1_Click()Randomize Timer
Dim i, j, k As Integer
i = Int(255 * Rnd) + 1
j = Int(255 * Rnd) + 1
k = Int(255 * Rnd) + 1
Cells(1, 1).Font.Color = RGB(i, j, k)
Cells(2, 1).Interior.Color = RGB(j, k, i)
End Sub

The Output

<<Lesson 15>> [Contents] <<Lesson 17>>

Понравилась статья? Поделить с друзьями:
  • Excel vba change all cells
  • Excel vba autofilter criteria not
  • Excel vba cells value get value
  • Excel vba autofilter array
  • Excel vba cells not empty