Изменение цвета текста (шрифта) в ячейке рабочего листа Excel с помощью кода VBA. Свойства ячейки (диапазона) .Font.Color, .Font.ColorIndex и .Font.TintAndShade.
Использование цветовой палитры для присвоения цвета тексту в ячейке листа Excel аналогично присвоению цвета фону ячейки, только свойство диапазона .Interior меняем на свойство .Font.
Цвет текста и предопределенные константы
Цвет шрифту в ячейке можно присвоить с помощью предопределенных констант:
Range(«A1:C3»).Font.Color = vbGreen Range(Cells(4, 1), Cells(6, 3)).Font.Color = vbBlue Cells(7, 1).Font.Color = vbRed |
Напомню, что вместо индексов строк и столбцов можно использовать переменные. Список предопределенных констант смотрите здесь.
Цвет шрифта и модель RGB
Для изменения цвета текста в ячейке можно использовать цветовую модель RGB:
Range(«A1»).Font.Color = RGB(200, 150, 250) Cells(2, 1).Font.Color = RGB(200, 150, 100) |
Аргументы функции RGB могут принимать значения от 0 до 255. Если все аргументы равны 0, цвет — черный, если все аргументы равны 255, цвет — белый. Функция RGB преобразует числовые значения основных цветов (красного, зеленого и синего) в индекс основной палитры.
Список стандартных цветов с RGB-кодами смотрите в статье: HTML. Коды и названия цветов.
Свойство .Font.ColorIndex
Свойство .Font.ColorIndex может принимать значения от 1 до 56. Это стандартная ограниченная палитра, которая существовала до Excel 2007 и используется до сих пор. Посмотрите примеры:
Range(«A1:D6»).Font.ColorIndex = 5 Cells(1, 6).Font.ColorIndex = 12 |
Таблица соответствия значений ограниченной палитры цвету:
Стандартная палитра Excel из 56 цветов
Подробнее о стандартной палитре Excel смотрите в статье: Стандартная палитра из 56 цветов.
Свойство .Font.ThemeColor
Свойство .Font.ThemeColor может принимать числовые или текстовые значения констант из коллекции MsoThemeColorIndex:
Range(«A1»).Font.ThemeColor = msoThemeColorHyperlink Cells(2, 1).Font.ThemeColor = msoThemeColorAccent4 |
Основная палитра
Основная палитра, начиная c Excel 2007, состоит из 16777216 цветов. Свойство .Font.Color может принимать значения от 0 до 16777215, причем 0 соответствует черному цвету, а 16777215 — белому.
Cells(1, 1).Font.Color = 0 Cells(2, 1).Font.Color = 6777215 Cells(3, 1).Font.Color = 4569325 |
Отрицательные значения свойства .Font.Color
При записи в Excel макрорекордером макроса с присвоением шрифту цвета используются отрицательные значения свойства .Font.Color, которые могут быть в пределах от -16777215 до -1. Отрицательные значения соответствуют по цвету положительному значению, равному сумме наибольшего индекса основной палитры и данного отрицательного значения. Например, отрицательное значение -8257985 соответствует положительному значению 8519230, являющегося результатом выражения 16777215 + (-8257985). Цвета текста двух ячеек из следующего кода будут одинаковы:
Cells(1, 1).Font.Color = —8257985 Cells(2, 1).Font.Color = 8519230 |
Свойство .Font.TintAndShade
Еще при записи макроса с присвоением шрифту цвета макрорекордером добавляется свойство .Font.TintAndShade, которое осветляет или затемняет цвет и принимает следующие значения:
- -1 — затемненный;
- 0 — нейтральный;
- 1 — осветленный.
При тестировании этого свойства в Excel 2016, сравнивая затемненные и осветленные цвета, разницы не заметил. Сравните сами:
Sub Test() With Range(Cells(1, 1), Cells(3, 1)) .Value = «Сравниваем оттенки» .Font.Color = 37985 End With Cells(1, 1).Font.TintAndShade = —1 Cells(2, 1).Font.TintAndShade = 0 Cells(3, 1).Font.TintAndShade = 1 End Sub |
В первые три ячейки первого столбца записывается одинаковый текст для удобства сравнения оттенков.
Разноцветный текст в ячейке
Отдельным частям текста в ячейке можно присвоить разные цвета. Для этого используется свойство Range.Characters:
Sub Test() With Range(«A1») .Font.Color = vbBlack .Value = «Океан — Солнце — Оазис» .Font.Size = 30 .Characters(1, 5).Font.Color = vbBlue .Characters(9, 6).Font.Color = RGB(255, 230, 0) .Characters(18, 5).Font.Color = RGB(119, 221, 119) End With End Sub |
Результат работы кода:
Return to VBA Code Examples
In this Article
- VBA Cell Font
- Change Font Color
- vbColor
- Color – RGB
- ColorIndex
- Font Size
- Bold Font
- Font Name
- Cell Style
VBA Cell Font
In VBA, you can change font properties using the VBA Font Property of the Range Object. Type the following code into the VBA Editor and you’ll see a list of all the options available:
Range("A1).Font.
We will discuss a few of the most common properties below.
Change Font Color
There are a few ways to set font colors.
vbColor
The easiest way to set colors is with vbColors:
Range("a1").Font.Color = vbRed
However, you’re very limited in terms of colors available. These are the only options available:
Color – RGB
You can also set colors based on RGB (Red Green Blue). Here you enter color values between 0-255 for Red, Green, and Blue. Using those three colors you can make any color:
Range("a1").Font.Color = RGB(255,255,0)
ColorIndex
VBA / Excel also has a ColorIndex property. This makes pre-built colors available to you. However, they’re stored as Index numbers, which makes it hard to know what color is what:
Range("a1").Font.ColorIndex = …..
We wrote an article about VBA Color codes, including a list of the VBA ColorIndex codes. There you can learn more about colors.
Font Size
This will set the font size to 12:
Range("a1").Font.Size = 12
or to 16:
Range("a1").Font.Size = 16
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Bold Font
It is easy to set a cell font to Bold:
Range("A1").Font.Bold = True
or to clear Bold formatting:
Range("A1").Font.Bold = False
Font Name
To change a font name use the Name property:
Range("A1").Font.Name = "Calibri"
Range("A1").Font.Name = "Arial"
Range("A1").Font.Name = "Times New Roman"
Cell Style
Excel offers the ability to create Cell “Styles”. Styles can be found in the Home Ribbon > Styles:
Styles allow you to save your desired Cell Formatting. Then assign that style to a new cell and all of the cell formatting is instantly applied. Including Font size, cell color, cell protections status, and anything else available from the Cell Formatting Menu:
Personally, for many of the models that I work on, I usually create an “Input” cell style:
Range("a1").Style = "Input"
By using styles you can also easily identify cell types on your worksheet. The example below will loop through all the cells in the worksheet and change any cell with Style = “Input” to “InputLocked”:
Dim Cell as Range
For Each Cell in ActiveSheet.Cells
If Cell.Style = "Input" then
Cell.Style = "InputLocked"
End If
Next Cell
Excel VBA Font Color
VBA Font Color property one may use to change the font color of Excel cells using VBA code. Using the color index and color property with the RGB function, we can change the font color in multiple ways.
When we prepare a dashboard in excelThe dashboard in excel is an enhanced visualization tool that provides an overview of the crucial metrics and data points of a business. By converting raw data into meaningful information, a dashboard eases the process of decision-making and data analysis.read more, we usually spend considerable time formatting cells, fonts, etc. Often, we feel like an Excel beautician by looking at the various colors of the Excel formatting. For example, changing the font color in an Excel worksheet is an easy job, but when it comes to Excel, you should know how to writing VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more to change the font color.
To change the font color, first, we need to identify what cells we are going to change.
Range (“A1:A10”)
Then we need to select the FONT property.
Range (“A1:A10”).Font
Then what do we want to do with this font? So, select color.
Range (“A1:A10”).Font.Color
Like this, we need to construct the code to change the font color. It does not look easy.
But remember, everything seems tough at the beginning. Later you will get the hang of it.
Table of contents
- Excel VBA Font Color
- How to Change Font Color using VBA?
- Example #1 – Using Color Index
- Example #2 – Using Color Property
- Example #3 – Using Color Property with RGB Function
- Recommended Articles
- How to Change Font Color using VBA?
How to Change Font Color using VBA?
You can download this VBA Font Color Excel Template here – VBA Font Color Excel Template
Example #1 – Using Color Index
The Color Index property is different from the Color property in VBAVBA Colour Index is used to change the colours of cells or cell ranges. This function has unique identification for different types of colours.read more. Using numerical values, we can change the color of cells and fonts.
Numbers range from 1 to 56, and each number represents different colors. Below is the list of numbers and their colors.
Let us test this out.
We have a value in cell A1.
We want to change the color of the cell A1 font to green. Below is the code.
Code:
Sub FontColor_Example1() Range("A1").Font.ColorIndex = 10 End Sub
It will change the color of the cell A1 font to green.
We can also use the CELLS property to change the color of the font.
Code:
Sub FontColor_Example1() Cells(1, 1).Font.ColorIndex = 10 End Sub
Like this, we can use numbers 1 to 56 to apply the desired color to the font.
Example #2 – Using Color Property
Color Index has very limited colors from 1 to 56, but using the COLOR property, we can use 8 built-in colors: vbBlack, vbRed, vbGreen, vbBlue, vbYellow, vbMagenta, vbCyan, vbWhite.
For these colors, we do not need to supply any numbers. Rather, we can access them using their name, as shown above. Below is the example code for all 8 colors.
Code:
Sub vbBlack_Example() Range("A1").Font.Color = vbBlack End Sub
Code:
Sub vbRed_Example() Range("A1").Font.Color = vbRed End Sub
Code:
Sub vbGreen_Example() Range("A1").Font.Color = vbGreen End Sub
Code:
Sub vbBlue_Example() Range("A1").Font.Color = vbBlue End Sub
Code:
Sub vbYellow_Example() Range("A1").Font.Color = vbYellow End Sub
Code:
Sub vbMagenta_Example() Range("A1").Font.Color = vbMagenta End Sub
Code:
Sub vbCyan_Example() Range("A1").Font.Color = vbCyan End Sub
Code:
Sub vbWhite_Example() Range("A1").Font.Color = vbWhite End Sub
Example #3 – Using Color Property with RGB Function
We have seen that we have only 8 built-in colors to work with. But we need to use the RGB function to have various colors. Besides built-in colors, we can create our colors by using the VBA VBA RGBRGB can be also termed as red green and blue, this function is used 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 considered as the components of these three different colors in VBA.read more function.
Look at the syntax of the RGB function.
RGB (Red, Green, Blue)
RGB stands for “Red, Green, and Blue.” Therefore, we need to supply numbers from 0 to 255 for each color to construct colors.
Below are a few examples for you.
Below are some of the macro code examples
Code:
Sub RGB_Example() Range("A1").Font.Color = RGB(0, 0, 0) 'Change the font colour to black End Sub
Code:
Sub RGB_Example() Range("A1").Font.Color = RGB(16, 185, 199) 'Font color will be this End Sub
Code:
Sub RGB_Example() Range("A1").Font.Color = RGB(106, 15, 19) 'Font color will be this End Sub
Code:
Sub RGB_Example() Range("A1").Font.Color = RGB(216, 55, 19) 'Font color will be this End Sub
Recommended Articles
This article has been a guide to VBA Font Color. Here, we learn how to change the font color by using the VBA color index, color property with RGB function along with examples, and download an Excel template. Below are some useful Excel articles related to VBA: –
- VBA Examples
- VBA ChDir
- Alternate Row Color in Excel
VBA Font Color
VBA has a lot of commands and functions to play with. We can do anything in VBA and apply that to Excel. Applying VBA in Excel is the easiest and a fun thing. VBA also has the function by which we can change the color of cell, fonts and we can even bold the characters as well. VBA font color is used in different ways and it helps to change the color of the fonts in excel.
How to Color a Font Using VBA?
Let’s see the examples of font color in Excel VBA.
You can download this VBA Font Color Excel Template here – VBA Font Color Excel Template
Example #1 – VBA Font Color
We have sample text in an Excel sheet with the text “VBA Font Color” in cell B3 as shown below. As we can see the color of the font is default black color in nature.
To apply the VBA code for changing the color of fonts for above-shown text, we need a module.
Step 1: So for this go to the VBA window and click on Module option available in the Insert menu option as shown below.
Step 2: Once we do that, we will get the blank window of Module. In that, start writing subcategory of VBA Font Color or in any other name as per your need as shown below.
Code:
Sub VBAFontColor2() End Sub
Step 3: First select the range of the cell where the text is located. Here, our range will be cell B3 and that will be written followed by “.Select” command as shown below.
Code:
Sub VBAFontColor2() Range("B3").Select End Sub
Step 4: As we need to change the color of fonts so we will select the Font command with the help of Selection as shown below.
Code:
Sub VBAFontColor2() Range("B3").Select Selection.Font End Sub
Step 5: After that, we will select the command Color separated by a dot (.) as shown below.
Code:
Sub VBAFontColor2() Range("B3").Select Selection.Font.Color End Sub
Now to understand the formation of any color, in VBA we have RGB i.e. Red-Green-Blue. Numeric values of each color range from 0 to 255. Suppose we need to change to a color font to Black then RGB value will be RGB(0, 0, 0). As we already have the black color font we will try to select some other color.
Step 6: Let’s give the largest value to Green color and least to Red and zero to Blue color. As per that, considering Red at 20, Green at 230 and Blue at zero as shown below.
Code:
Sub VBAFontColor2() Range("B3").Select Selection.Font.Color = RGB(20, 230, 0) End Sub
Step 7: Now compile the code to find if it has any error and then run by clicking on the play button located below the menu bar. We will apply font color for text which is in cell B3 and now changed from Black to Green color.
Example #2 – VBA Font Color
There is another way of changing the font color in VBA. For this, we will consider the same text as shown in example-1 located in cell B3.
Apart from RGB, we can change the color of fonts with the keyword “vb” followed by the name of the color. But by this process, we can only get the main basic color as the font color. Where with the help of RGB we could get color of any shade, just by putting the different values for Red, Green and Blue colors.
The color which can be used with vb are Black, Blue, Cyan, Green, Magenta, Red, White, and Yellow. And how to select the color in format is shown below.
Step 1: To apply this, go to VBA to create the subcategory in the name of VBA Font Color or in any other name in a new module as shown below.
Code:
Sub VBAFontColor3() End Sub
Step 2: Select the range of cell for which we need to change the font color as shown below.
Code:
Sub VBAFontColor3() Range("B3").Select End Sub
Step 3: In the same manner what we have seen in example-1, use selection function with Font and Color to activate them.
Code:
Sub VBAFontColor3() Range("B3").Select Selection.Font.Color End Sub
Step 4: It lets the color of font from Black to Cyan. For this select Cyan color by vbCyan as shown below.
Code:
Sub VBAFontColor3() Range("B3").Select Selection.Font.Color = vbCyan End Sub
Step 5: If required then we can compile the code and then run it. We will see the font color of text at cell B3 is changed from Black to Cyan.
Example #3 – VBA Font Color
Microsoft has defined a variety of color in different numbers. These are 56 in numbers. We can select any of the color code between to 1 to 56 to change the font color of any cell. These color codes are shown below.
Step 1: Now go to the VBA window and open a new module. In that write the Sub Category of VBA Font Color as shown below.
Code:
Sub VBAFontColor4() End Sub
Step 2: For this example, we will select the same text as seen in the above examples. Now select the range of the cell which is B3 as shown below.
Code:
Sub VBAFontColor4() Range("B3").Select End Sub
Step 3: Now in the second line, select the Font function with Selection command.
Code:
Sub VBAFontColor4() Range("B3").Select Selection.Font. End Sub
Step 4: To select and apply the above-shown color code, we need to select ColorIndex function instead of Color which we used in example 1 and 2.
Code:
Sub VBAFontColor4() Range("B3").Select Selection.Font.ColorIndex = 46 End Sub
And at last, select the color code which we need to see in a selected range of cell. Let’s select color code 46 which is used for Orange color.
Step 5: Now run the code to see the change. We will the color font at cell B3 is now changed from black to orange.
Pros of VBA Font Color
- It is easy to implement.
- With the help of RGB, we can change the color of any shade we want.
- It helps in creating the dashboard where we need to show the different types of data in a different color with the help of VBA.
Things to Remember
- It is always recommended to use RGB when we do not know the color code. By giving a different color range from 0 to 255 in RGB we can create any color from dark to bright shade of our choice.
- Saving the file in Macro Enable Excel helps to use and visit the written code multiple times.
- Although changing font color in excel is the easiest way to do, but automating this activity in huge set of work can save the time and it will avoid the chances when the file may get crash or hang.
Recommended Articles
This is a guide to VBA Font Color. Here we discuss how to use Excel VBA Font Color along with few practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA While Loop
- VBA Remove Duplicates
- VBA Data Types
- VBA Sleep
Written by Puneet for Excel 2007, Excel 2010, Excel 2013, Excel 2016, Excel 2019, Excel for Mac
Key Notes
- To make changes in a font, you need to use the VBA Font object.
- There is a total of 18 properties with the font object that you can access and make changes.
VBA Font Object
In VBA, there is a font object which you can use to change properties of the font from a cell, like, font color, font size, font type, and you can also apply bold and italic to the font.
Syntax
expression.font
To use it, first, you need to define the cell address, which you can specify in the following ways.
Selection.Font
Range("A1").Font
Cells(1, 1).Font
Range("A1:A5").Font
To change the color of the font, you have two different ways:
1. Using Color Constants
Excel has a few color constants that you can use to apply color to the font. For example, if you want to apply the red color to the font in cell A1, the code would be like the below:
Range("A1").Font.Color = vbRed
In the above code, after the font object, color is the property and you have used the vbRed constant that tells VBA to apply the red color to the cell A1. There is a total of eight constants that you can use:
- vbBlack: Black
- vbRed: Red
- vbGreen: Green
- vbYellow: Yellow
- vbBlue: Blue
- vbMagenta: Magenta
- vbCyan: Cyan
- vbWhite: White
2. Using RGB
You can also use the RGB color code to apply color to the font. RGB is the combination of red, green, and blue colors, where you can create a custom color using the code. Let’s say if you want to apply a combination of green and blue color to cell A1 the code would be:
Range("A1").Font.Color = RGB(0, 255, 255)
VBA Font Size
Font object also gives you access to the size property of the font. Let’s say you want to apply the font size of 16 to the font in the cell A1, the code would be:
Range("A1").Font.Size = 16
If you want to apply font size to all cells in a worksheet you can use the following code:
Cells.Font.Size = 16
And if only want to apply font size to cells where you have data, the code would be:
ActiveSheet.UsedRange.Font.Size = 16
Or to the selected cell.
Selection.Font.Size = 16
VBA Font Name
In the same way, you can also change the font name using the name property of the font object. Let’s say you want to apply the “Consolas” font the cell A1. The code would be:
Range("A1").Font.Name = "Consolas"
While using this property, you need to type the correct name of the font that you want to apply, and if somehow the name is incorrect, it won’t show you an error.
VBA Font Bold, Italic, and Underline
There are also properties that you can use to make the font bold, italic, and underline. Below are the codes that you need to write for this.
Range("A1").Font.Bold = True
Range("A1").Font.Italic = True
Range("A1").Font.Underline = True
With these properties, you need to define TRUE or FALSE. So if the font is already bold or italic and you want to remove it, then you need to use FALSE to remove them.
Other Useful Font Properties
Here add a few more properties that can be useful for you (Strikethrough, Subscript, and Superscript).
Range("A1").Font.Strikethrough = True
Range("A1").Font.Subscript = True
Range("A1").Font.Superscript = True
More Tutorials
- Count Rows using VBA in Excel
- Excel VBA Hide and Unhide a Column or a Row
- Excel VBA Range – Working with Range and Cells in VBA
- Apply Borders on a Cell using VBA in Excel
- Find Last Row, Column, and Cell using VBA in Excel
- Insert a Row using VBA in Excel
- Merge Cells in Excel using a VBA Code
- Select a Range/Cell using VBA in Excel
- SELECT ALL the Cells in a Worksheet using a VBA Code
- ActiveCell in VBA in Excel
- Special Cells Method in VBA in Excel
- UsedRange Property in VBA in Excel
- VBA AutoFit (Rows, Column, or the Entire Worksheet)
- VBA ClearContents (from a Cell, Range, or Entire Worksheet)
- VBA Copy Range to Another Sheet + Workbook
- VBA Enter Value in a Cell (Set, Get and Change)
- VBA Insert Column (Single and Multiple)
- VBA Named Range | (Static + from Selection + Dynamic)
- VBA Range Offset
- VBA Sort Range | (Descending, Multiple Columns, Sort Orientation
- VBA Wrap Text (Cell, Range, and Entire Worksheet)
- VBA Check IF a Cell is Empty + Multiple Cells
⇠ Back to What is VBA in Excel
Helpful Links – Developer Tab – Visual Basic Editor – Run a Macro – Personal Macro Workbook – Excel Macro Recorder – VBA Interview Questions – VBA Codes
Цвет шрифта Excel VBA
Свойство VBA Font Color можно использовать для изменения цвета шрифта ячеек Excel с помощью кода VBA. Используя индекс цвета и свойство цвета с функцией RGB, мы можем изменить цвет шрифта несколькими способами.
Когда мы готовим информационную панель в excelПодготовка информационной панели в ExcelИнформационная панель в Excel — это расширенный инструмент визуализации, который предоставляет обзор важнейших показателей и точек данных для бизнеса. Преобразовывая необработанные данные в содержательную информацию, информационная панель упрощает процесс принятия решений и анализа данных. Подробнее, мы обычно тратим много времени на форматирование ячеек, шрифты и т. д. Часто мы чувствуем себя косметологами Excel, глядя на различные цвета. форматирования Excel. Например, изменение цвета шрифта на листе Excel — простая задача, но когда дело доходит до Excel, вы должны знать, как писать код VBA. Написание кода VBA Код VBA — это набор инструкций, написанных пользователем в программировании приложений Visual Basic. языка в редакторе Visual Basic (VBE) для выполнения определенной задачи. Подробнее об изменении цвета шрифта.
Чтобы изменить цвет шрифта, во-первых, нам нужно определить, какие ячейки мы собираемся изменить.
Диапазон («A1:A10»)
Затем нам нужно выбрать свойство FONT.
Диапазон («A1:A10»). Шрифт
Тогда что мы хотим сделать с этим шрифтом? Итак, выберите цвет.
Диапазон («A1:A10»). Шрифт. Цвет
Таким образом, нам нужно создать код для изменения цвета шрифта. Это не выглядит легко.
Но помните, вначале все кажется трудным. Позже вы освоитесь.
Оглавление
- Цвет шрифта Excel VBA
- Как изменить цвет шрифта с помощью VBA?
- Пример №1 – Использование цветового индекса
- Пример №2 – Использование свойства цвета
- Пример №3 – Использование свойства цвета с функцией RGB
- Рекомендуемые статьи
- Как изменить цвет шрифта с помощью VBA?
Как изменить цвет шрифта с помощью VBA?
.free_excel_div{фон:#d9d9d9;размер шрифта:16px;радиус границы:7px;позиция:относительная;margin:30px;padding:25px 25px 25px 45px}.free_excel_div:before{content:»»;фон:url(центр центр без повтора #207245;ширина:70px;высота:70px;позиция:абсолютная;верх:50%;margin-top:-35px;слева:-35px;граница:5px сплошная #fff;граница-радиус:50%} Вы можете скачать этот шаблон Excel цвета шрифта VBA здесь — Цвет шрифта VBA Шаблон Excel
Пример №1 – Использование цветового индекса
Свойство Color Index отличается от свойства Color в VBAColor Свойство В VBAVBA Color Index используется для изменения цветов ячеек или диапазонов ячеек. Эта функция имеет уникальную идентификацию для различных типов цветов.Подробнее. Используя числовые значения, мы можем изменить цвет ячеек и шрифтов.
Числа варьируются от 1 до 56, и каждое число представляет разные цвета. Ниже приведен список чисел и их цветов.
Давайте проверим это.
У нас есть значение в ячейке A1.
Мы хотим изменить цвет шрифта ячейки A1 на зеленый. Ниже приведен код.
Код:
Sub FontColor_Example1() Range («A1»). Font.ColorIndex = 10 End Sub
Это изменит цвет шрифта ячейки A1 на зеленый.
Мы также можем использовать свойство CELLS для изменения цвета шрифта.
Код:
Sub FontColor_Example1() Cells(1, 1).Font.ColorIndex = 10 End Sub
Таким образом, мы можем использовать числа от 1 до 56, чтобы применить желаемый цвет к шрифту.
Пример №2 – Использование свойства цвета
Color Index имеет очень ограниченное количество цветов от 1 до 56, но с помощью свойства COLOR мы можем использовать 8 встроенных цветов: vbBlack, vbRed, vbGreen, vbBlue, vbYellow, vbMagenta, vbCyan, vbWhite.
Для этих цветов нам не нужно указывать какие-либо числа. Скорее, мы можем получить к ним доступ, используя их имя, как показано выше. Ниже приведен пример кода для всех 8 цветов.
Код:
Sub vbBlack_Example() Range(«A1»).Font.Color = vbBlack End Sub
Код:
Sub vbRed_Example() Range(«A1»).Font.Color = vbRed End Sub
Код:
Sub vbGreen_Example() Range(«A1»).Font.Color = vbGreen End Sub
Код:
Sub vbBlue_Example() Range(«A1»).Font.Color = vbBlue End Sub
Код:
Sub vbYellow_Example() Range(«A1»).Font.Color = vbYellow End Sub
Код:
Sub vbMagenta_Example() Range(«A1»).Font.Color = vbMagenta End Sub
Код:
Sub vbCyan_Example() Range(«A1»).Font.Color = vbCyan End Sub
Код:
Sub vbWhite_Example() Range(«A1»).Font.Color = vbWhite End Подпример №3 — Использование свойства цвета с функцией RGB
Мы видели, что у нас есть только 8 встроенных цветов для работы. Но нам нужно использовать функцию RGB, чтобы иметь разные цвета. Помимо встроенных цветов, мы можем создавать наши цвета с помощью VBA VBA RGBVBA RGBRGB также можно назвать красным, зеленым и синим, эта функция используется для получения числового значения значения цвета, эта функция имеет три компонента: диапазон, и они красный, синий и зеленый, другие цвета рассматриваются как компоненты этих трех разных цветов в функции VBA.
Посмотрите на синтаксис функции RGB.
RGB (красный, зеленый, синий)
RGB означает «красный, зеленый и синий». Поэтому нам нужно предоставить числа от 0 до 255 для каждого цвета, чтобы построить цвета.
Ниже приведены несколько примеров для вас.
Ниже приведены некоторые примеры кода макроса.
Код:
Sub RGB_Example() Range(«A1»).Font.Color = RGB(0, 0, 0) ‘Изменить цвет шрифта на черный End Sub
Код:
Sub RGB_Example() Range(«A1»).Font.Color = RGB(16, 185, 199) ‘Цвет шрифта будет этим End Sub
Код:
Sub RGB_Example() Range(«A1»).Font.Color = RGB(106, 15, 19) ‘Цвет шрифта будет этим End Sub
Код:
Sub RGB_Example() Range(«A1»).Font.Color = RGB(216, 55, 19) ‘Цвет шрифта будет этим End Sub
Рекомендуемые статьи
Эта статья была руководством по цвету шрифта VBA. Здесь мы узнаем, как изменить цвет шрифта, используя индекс цвета VBA, свойство цвета с функцией RGB вместе с примерами и загрузим шаблон Excel. Ниже приведены некоторые полезные статьи Excel, связанные с VBA:
- Примеры VBA
- ЧДир ВБА
- Альтернативный цвет строки в Excel
In this Excel VBA Change Font Color Based on Cell Value Tutorial, you learn how to change a cell’s font color based on a cell’s value with Excel macros.
You can (also) change a cell’s font color based on a cell’s value with Excel’s Conditional Formatting. In some cases, Conditional Formatting may be the more appropriate tool (instead of VBA macros) to change a cell’s font color based on a cell’s value.
This Excel VBA Change Font Color Based on Cell Value Tutorial is accompanied by an Excel workbook with the data and VBA code I use when describing the step-by-step process below. Get this example workbook (for free) by clicking the button below.
The VBA code in the Excel workbook that accompanies this Excel VBA Change Font Color Based on Cell Value Tutorial is (always) stored in the Visual Basic Editor (VBE). If you don’t know how to work with the VBE, I suggest you read my Visual Basic Editor (VBE) Tutorial. I link to this Tutorial in the Related Excel Macro and VBA Training Materials and Resources Section below.
The following Excel Macro and VBA Tutorials may help you better understand and implement the contents below.
- Tutorials about general macro and VBA constructs and structures:
- Tutorials for Beginners:
- Excel Macros: Click here to open.
- Excel VBA: Click here to open.
- Enable macros in Excel: Click here to open.
- Work with the Visual Basic Editor (VBE): Click here to open.
- Create Sub procedures: Click here to open.
- Refer to objects (click here to open), including:
- Sheets: Click here to open.
- Cell ranges: Click here to open.
- Work with:
- Properties: Click here to open.
- Variables: Click here to open.
- Data types: Click here to open.
- Functions: Click here to open.
- Events: Click here to open.
- R1C1-style references: Click here to open.
- The Select Case statement: Click here to open.
- Loops: Click here to open.
- Tutorials for Beginners:
- Tutorials with practical VBA applications and macro examples:
- Activate a workbook: Click here to open.
- Find the last row and last column: Click here to open.
- Work with the Value property: Click here to open.
- Check if a cell is empty: Click here to open.
- Work with font characteristics: Click here to open.
- Work with Excel’s AutoFilter: Click here to open.
- Search and find: Click here to open.
This Excel VBA Change Font Color Based on Cell Value Tutorial is part of a more comprehensive series of Excel VBA Font Color Tutorials.
- Excel VBA Font Color Index in 2 Easy Steps: Click here to open.
- Excel VBA Font Color RGB in 2 Easy Steps: Click here to open.
- Excel VBA Font Color HEX in 5 Easy Steps: Click here to open.
- Excel VBA Change Font Color for Part of Text in 8 Easy Steps: Click here to open.
- Excel VBA Text Box Font Color in 2 Easy Steps: Click here to open.
- Excel VBA ActiveX Text Box Font Color in 2 Easy Steps: Click here to open.
- Excel VBA UserForm Text Box Font Color in 2 Easy Steps: Click here to open.
- Excel VBA Chart Data Label Font Color in 4 Easy Steps: Click here to open.
- Excel VBA ActiveX Label Font Color in 2 Easy Steps: Click here to open.
- Excel VBA UserForm Label Font Color in 2 Easy Steps: Click here to open.
You can find more Excel and VBA Tutorials in the organized Tutorials Archive: Click here to visit the Archives.
If you want to learn how to automate Excel (and save time) by working with macros and VBA, you may be interested in the following Premium Excel Macro and VBA Training Materials:
- Premium Courses at the Power Spreadsheets Academy: Click here to open.
- Books at the Power Spreadsheets Library: Click here to open.
- VBA Cheat Sheets: Click here to open.
If you want to save time when working with macros and VBA, you may be interested in AutoMacro: Click here to learn more about AutoMacro (affiliate link). AutoMacro is an add-in for VBA that installs directly into the VBE. Depending on the version, AutoMacro comes loaded with:
- Code generators.
- An extensive code library.
- The ability to create your own code library.
- Advanced coding tools.
If you need consulting services, you may want to consider working with ExcelRescue. ExcelRescue is my usual suggestion for people who (like you) may need help with Excel tasks/projects: Click here to visit ExcelRescue (affiliate link).
The VBA Change Font Color Based on Cell Value Snippet Template/Structure
The following are the 2 versions of the VBA change font color based on cell value snippet template/structure I explain (step-by-step) in the Sections below.
If… Then… Else Statement Version of the VBA Change Font Color Based on Cell Value Snippet Template/Structure
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ If WorkbookObjectReferenceForValue.WorksheetObjectReferenceForValue.CellRangeObjectReferenceForValue.Value ComparisonOperator CriterionValue Then CellRangeObjectReferenceForFontColor.Font.ColorOrColorIndex = NewColorOrColorIndexValueIfTrue End If
Select Case Statement Version of the VBA Change Font Color Based on Cell Value Snippet Template/Structure
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ Select Case WorkbookObjectReferenceForValue.WorksheetObjectReferenceForValue.CellRangeObjectReferenceForValue.Value Case CriterionValue1: CellRangeObjectReferenceForFontColor.Font.ColorOrColorIndex = NewColorOrColorIndexValue1 Case CriterionValue2: CellRangeObjectReferenceForFontColor.Font.ColorOrColorIndex = NewColorOrColorIndexValue2 '... Case CriterionValue#: CellRangeObjectReferenceForFontColor.Font.ColorOrColorIndex = NewColorOrColorIndexValue# Case Else: CellRangeObjectReferenceForFontColor.Font.ColorOrColorIndex = NewColorOrColorIndexValueElse End Select
The Example Before VBA Change Font Color Based on Cell Value
This Excel VBA Change Font Color Based on Cell Value Tutorial is accompanied by an Excel workbook with the data and VBA code I use when describing the step-by-step process below. Get this example workbook (for free) by clicking the button below.
The VBA code in the Excel workbook that accompanies this Excel VBA Change Font Color Based on Cell Value Tutorial is (always) stored in the Visual Basic Editor (VBE). If you don’t know how to work with the VBE, I suggest you read my Visual Basic Editor (VBE) Tutorial. I link to this Tutorial in the Related Excel Macro and VBA Training Materials and Resources Section above.
The example worksheet has 1 table (cells A6 to B26) with the following characteristics:
- 2 columns (Value, Change Font Color Based on Cell Value Result).
- 1 header row (row 6).
- 20 entries (rows 7 to 26).
Step 1: Refer to the Cell Whose Value You Consider
Refer to the cell whose value you consider when changing a cell’s font color.
In other words: Create a VBA expression that returns a Range object representing the cell whose value determines the font color.
Consider explicitly including the following references to create a fully qualified object reference returning a Range object:
- A reference to the applicable workbook. The following VBA constructs (among others) may return a Workbook object:
- The Application.ThisWorkbook property.
- The Application.Workbooks and Workbooks.Item properties.
- The Application.ActiveWorkbook property.
- A reference to the applicable worksheet. The following VBA constructs (among others) may return a Worksheet object:
- The Workbook.Sheets and Sheets.Item properties.
- The Workbook.Worksheets and Worksheets.Item properties.
- The Application.ActiveSheet property.
- A reference to the applicable cell range. The following VBA constructs (among others) may return a Range object:
- The Worksheet.Range property.
- The Worksheet.Cells and Range.Item properties.
- The Worksheet.Rows property.
- The Worksheet.Columns property.
- The Range.Range property.
- The Range.Cells and Range.Item properties.
- The Range.Rows property.
- The Range.Columns property.
- The Range.EntireRow property.
- The Range.EntireColumn property.
- The Range.Offset property.
- The Range.CurrentRegion property.
- The Range.End property.
- The Range.Resize property.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ WorkbookObjectReferenceForValue.WorksheetObjectReferenceForValue.CellRangeObjectReferenceForValue
Step 1 Example
I do the following:
(1) Declare an object variable:
- As of the Range object data type.
- With the name “iCell”.
- To act as the iteration object variable for the For Each… Next loop I create below.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ Dim iCell As Range
(2) Create a For Each… Next loop with the following characteristics:
- The iCell object variable is the loop’s iteration object variable.
- The loop iterates through all cells between cell A7 and cell A26 in the “VBA Font Color Based on Value” worksheet in the workbook where the procedure is stored.
I work with the following constructs to obtain the cell range the For Each… Next loop works with:
- The Application.ThisWorkbook property: ThisWorkbook.
- The Workbook.Worksheets and Worksheets.Item properties: Worksheets(“VBA Font Color Based on Value”).
- The Worksheet.Range property: Range(“A7:A26”).
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ Dim iCell As Range For Each iCell In ThisWorkbook.Worksheets("VBA Font Color Based on Value").Range("A7:A26") '... Next iCell
The iCell object variable represents the cell the loop is currently iterating through.
Step 2: Test the Cell’s Value, and Instruct Excel to Execute the Applicable Statement (Changing a Cell’s Font Color) Depending on the Cell’s Value
Work with one of the following statements to conditionally execute a statement (changing a cell’s font color):
- If… Then… Else.
- Select Case.
If… Then… Else Statement Version
If you choose to work with the If… Then… Else statement to conditionally execute the statement changing a cell’s font color:
- The conditional test(s) (on which statement execution depends) test(s) whether the value stored in the cell whose value you consider when changing a cell’s font color (which you refer to in step #1) meets the applicable condition (for changing font color).
- The statement to execute (depending on the value returned by the applicable conditional test(s)) is that changing the applicable cell’s font color. You build this statement in step #4.
Depending on the case you deal with, you may need to work with different versions of the If… Then… Else statement. Consider the following 4 basic versions of the If… Then… Else statement:
- If… Then. This is the version I use in this Excel VBA Change Font Color Based on Cell Value Tutorial.
- If… Then… Else.
- If… Then… ElseIf.
- If… Then… ElseIf… Else.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ If ConditionalTest Then StatementFromStep4 End If
Use the following 3 elements to create the conditional test(s) inside the If… Then… Else statement:
- The value stored in the cell (whose value you consider when changing a cell’s font color).
- You created the applicable Range object reference in step #1.
- As a general rule: Work with the Range.Value property to get the cell’s value.
- A comparison operator.
- Comparison operators:
- Carry out comparisons.
- (Usually) Return a Boolean value (True or False).
- The following are commonly used comparison operators:
- Less than (<).
- Less than or equal to (<=).
- Greater than (>).
- Greater than or equal to (>=).
- Equal to (=).
- Not equal to (<>).
- Comparison operators:
- An expression with the criterion (value) you use to determine whether the condition (for changing a cell’s font color) is met.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ WorkbookObjectReferenceForValue.WorksheetObjectReferenceForValue.CellRangeObjectReferenceForValue.Value ComparisonOperator CriterionValue
Considering both:
- The If… Then… Else statement; and
- The conditional test;
The basic template/structure of the full If… Then block is as follows:
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ If WorkbookObjectReferenceForValue.WorksheetObjectReferenceForValue.CellRangeObjectReferenceForValue.Value ComparisonOperator CriterionValue Then StatementFromStep4 End If
Select Case Statement Version
Start with the basic Select Case statement structure/template.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ Select Case TestExpression Case CaseExpression1: CaseStatement1 Case CaseExpression2: CaseStatement2 '... Case CaseExpression#: CaseStatement# Case Else: ElseStatement End Select
If you choose to work with the Select Case statement to conditionally execute the statement changing a cell’s font color:
- The test expression used to identify the statement (changing a cell’s font color) to execute is the value stored in the cell (whose value you consider when changing a cell’s font color).
- You created the applicable Range object reference in step #1.
- As a general rule: Work with the Range.Value property to get the cell’s value.
- The case expressions used to identify the statement (changing a cell’s font color) to execute are the criteria (values) you use to determine the statement (changing a cell’s font color) to execute.
- The statement to execute (for each case expression) is that changing the applicable cell’s font color. You build this statement in step #4.
Therefore, the basic template/structure of the Select Case block is as follows:
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ Select Case WorkbookObjectReferenceForValue.WorksheetObjectReferenceForValue.CellRangeObjectReferenceForValue.Value Case CriterionValue1: StatementFromStep4ForValue1 Case CriterionValue2: StatementFromStep4ForValue2 '... Case CriterionValue#: StatementFromStep4ForValue# Case Else: StatementFromStep4ForElse End Select
Step 2 Example
The statements inside the Select Case block in the VBA font color based on value example macro start with a reference to the cell the loop is currently iterating through (represented by the iCell object variable I declared in step #1).
Therefore, I work with a With… End With block. The statements inside the With… End With block work with the cell represented by the iCell object variable.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ With iCell Select Case TestExpression Case CaseExpression1: CaseStatement1 Case CaseExpression2: CaseStatement2 '... Case CaseExpression#: CaseStatement# Case Else: ElseStatement End Select End With
The test expression inside the Select Case statement is the value stored in the cell represented by the iCell object variable. I use the Range.Value property to get this cell’s value.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ With iCell Select Case .Value Case CaseExpression1: CaseStatement1 Case CaseExpression2: CaseStatement2 '... Case CaseExpression#: CaseStatement# Case Else: ElseStatement End Select End With
The case expressions inside the Select Case statement are the following values:
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ With iCell Select Case .Value Case 1: CaseStatement1 Case 2: CaseStatement2 Case 3: CaseStatement3 Case 4: CaseStatement4 Case 5: CaseStatement5 Case 6: CaseStatement6 Case 7: CaseStatement7 Case 8: CaseStatement8 End Select End With
The statement to execute (for each case expression inside the Select Case statement) is that changing the applicable cell’s font color. I build this statement in step #4.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ With iCell Select Case .Value Case 1: StatementFromStep4ForValue1 Case 2: StatementFromStep4ForValue2 Case 3: StatementFromStep4ForValue3 Case 4: StatementFromStep4ForValue4 Case 5: StatementFromStep4ForValue5 Case 6: StatementFromStep4ForValue6 Case 7: StatementFromStep4ForValue7 Case 8: StatementFromStep4ForValue8 End Select End With
Step 3: Refer to the Cell Whose Font Color You Change (Based on a Cell’s Value)
Refer to the cell whose font color you change (based on a cell’s value).
In other words: Create a VBA expression that returns a Range object representing the cell whose font color you change (based on a cell’s value).
The cell whose font color you change (based on a cell’s value) can be either of the following:
- The same cell whose value you consider (when changing the cell’s font color). You created the applicable Range object reference in step #1.
- A different cell from that whose value you consider (when changing a cell’s font color).
Consider whether explicitly including the following references to create a fully qualified object reference returning a Range object is necessary (or advisable):
- A reference to the applicable workbook.
- A reference to the applicable worksheet.
- A reference to the applicable cell range.
In step #1, I list several VBA constructs that may return a Workbook object, a Worksheet object, or a Range object.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ CellRangeObjectReferenceForFontColor
Step 3 Example
I work with the Range.Offset property to refer to the cell one column to the right of the cell represented by the iCell object variable (I declared in step #1). I set the parameters of the Range.Offset property as follows:
- RowOffset: 0.
- ColumnOffset: 1.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ iCell.Offset(0, 1)
Step 4: Set the Value of the Font.Color or Font.ColorIndex Property
Use either of the following 2 properties to set the applicable cell’s font color:
- Font.Color.
- Font.ColorIndex.
Do the following to set the value of the Font.Color or Font.ColorIndex property:
(1) Start with the Range object reference you created in step #3.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ CellRangeObjectReferenceForFontColor
(2) Refer to the following:
- The Range.Font property; and
- The Font.Color or Font.ColorIndex property (as applicable).
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ CellRangeObjectReferenceForFontColor.Font.ColorOrColorIndex
(3) Set the value of the Font.Color property or Font.ColorIndex property.
If you don’t know how to work with the Font.Color or Font.ColorIndex properties, I suggest you read the applicable Tutorials I link to in the Related Excel Macro and VBA Training Materials and Resources Section above.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ CellRangeObjectReferenceForFontColor.Font.ColorOrColorIndex = NewColorOrColorIndexValue
(4) Add the statement(s) setting the value of the Font.Color or Font.ColorIndex property to (as applicable):
- The If… Then… Else statement; or
- The Select Case statement.
You created the applicable (If… Then… Else or Select Case) statement in step #2.
Depending on the case you deal with, you may have to add several statements setting the value of the Font.Color or Font.ColorIndex property. The following are situations where this may happen:
- If you work with one of the following versions of the If… Then… Else statement:
- If… Then… Else.
- If… Then… ElseIf.
- If… Then… ElseIf… Else.
- If your Select Case statement has several case expressions.
As a general rule: The basic template/structure (of the statement(s) setting the value of the Font.Color or Font.ColorIndex property) you learn in this Section is applicable to those (several) statements.
If… Then… Else Statement Version
(1) Start with the If… Then… Else statement you created in step #2.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ If WorkbookObjectReferenceForValue.WorksheetObjectReferenceForValue.CellRangeObjectReferenceForValue.Value ComparisonOperator CriterionValue Then StatementFromStep4 End If
(2) When considering the statement (setting the value of the Font.Color or Font.ColorIndex property) you create in this step #4:
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ If WorkbookObjectReferenceForValue.WorksheetObjectReferenceForValue.CellRangeObjectReferenceForValue.Value ComparisonOperator CriterionValue Then CellRangeObjectReferenceForFontColor.Font.ColorOrColorIndex = NewColorOrColorIndexValue End If
Select Case Statement Version
(1) Start with the Select Case statement you created in step #2.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ Select Case WorkbookObjectReferenceForValue.WorksheetObjectReferenceForValue.CellRangeObjectReferenceForValue.Value Case CriterionValue1: StatementFromStep4ForValue1 Case CriterionValue2: StatementFromStep4ForValue2 '... Case CriterionValue#: StatementFromStep4ForValue# Case Else: StatementFromStep4ForElse End Select
(2) When considering the statements (setting the value of the Font.Color or Font.ColorIndex property) you create in this step #4:
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ Select Case WorkbookObjectReferenceForValue.WorksheetObjectReferenceForValue.CellRangeObjectReferenceForValue.Value Case CriterionValue1: CellRangeObjectReferenceForFontColor.Font.ColorOrColorIndex = NewColorOrColorIndexValue1 Case CriterionValue2: CellRangeObjectReferenceForFontColor.Font.ColorOrColorIndex = NewColorOrColorIndexValue2 '... Case CriterionValue#: CellRangeObjectReferenceForFontColor.Font.ColorOrColorIndex = NewColorOrColorIndexValue# Case Else: CellRangeObjectReferenceForFontColor.Font.ColorOrColorIndex = NewColorOrColorIndexValueElse End Select
Step 4 Example
(1) I start with the Select Case statement I created in step #2.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ With iCell Select Case .Value Case 1: StatementFromStep4ForValue1 Case 2: StatementFromStep4ForValue2 Case 3: StatementFromStep4ForValue3 Case 4: StatementFromStep4ForValue4 Case 5: StatementFromStep4ForValue5 Case 6: StatementFromStep4ForValue6 Case 7: StatementFromStep4ForValue7 Case 8: StatementFromStep4ForValue8 End Select End With
(2) The Select Case statement requires 8 different versions of the statement setting the value of the Font.Color or Font.ColorIndex property.
I set the value of the Font.Color property to the following VBA color constants:
- vbBlack.
- vbRed.
- vbGreen.
- vbYellow.
- vbBlue.
- vbMagenta.
- vbCyan.
- vbWhite.
Considering the Range object reference I created in step #3:
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ iCell.Offset(0, 1).Font.Color = vbBlack iCell.Offset(0, 1).Font.Color = vbRed iCell.Offset(0, 1).Font.Color = vbGreen iCell.Offset(0, 1).Font.Color = vbYellow iCell.Offset(0, 1).Font.Color = vbBlue iCell.Offset(0, 1).Font.Color = vbMagenta iCell.Offset(0, 1).Font.Color = vbCyan iCell.Offset(0, 1).Font.Color = vbWhite
(3) I add these statements (setting the value of the Font.Color property) to the Select Case block.
Considering the With… End With block I created in step #2, I remove the explicit references to the iCell object variable in the individual statements inside the Select Case block.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ With iCell Select Case .Value Case 1: .Offset(0, 1).Font.Color = vbBlack Case 2: .Offset(0, 1).Font.Color = vbRed Case 3: .Offset(0, 1).Font.Color = vbGreen Case 4: .Offset(0, 1).Font.Color = vbYellow Case 5: .Offset(0, 1).Font.Color = vbBlue Case 6: .Offset(0, 1).Font.Color = vbMagenta Case 7: .Offset(0, 1).Font.Color = vbCyan Case 8: .Offset(0, 1).Font.Color = vbWhite End Select End With
(4) I nest this With… End With block inside the For Each… Next loop I created in step #1.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ Dim iCell As Range For Each iCell In ThisWorkbook.Worksheets("VBA Font Color Based on Value").Range("A7:A26") With iCell Select Case .Value Case 1: .Offset(0, 1).Font.Color = vbBlack Case 2: .Offset(0, 1).Font.Color = vbRed Case 3: .Offset(0, 1).Font.Color = vbGreen Case 4: .Offset(0, 1).Font.Color = vbYellow Case 5: .Offset(0, 1).Font.Color = vbBlue Case 6: .Offset(0, 1).Font.Color = vbMagenta Case 7: .Offset(0, 1).Font.Color = vbCyan Case 8: .Offset(0, 1).Font.Color = vbWhite End Select End With Next iCell
The full VBA font color based on value example macro is as follows:
Sub ChangeFontColorBasedOnCellValue() 'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-font-color-value/ 'Step 1: Declare iteration object variable Dim iCell As Range 'Step 1: Loop through all cells between cells A7 and A26 in the "VBA Font Color Based on Value" worksheet in this workbook For Each iCell In ThisWorkbook.Worksheets("VBA Font Color Based on Value").Range("A7:A26") 'Step 1: Refer to the cell the loop is currently iterating through With iCell 'Step 2: Use the value stored in the cell the loop is currently iterating through to identify the statement to execute Select Case .Value 'Do the following: 'Step 2: Execute the applicable statement (based on the applicable cell value) 'Step 3: Refer to the cell one column to the right of the cell the loop is currently iterating through 'Step 4: Set the value of the Font.Color property to a VBA color constant Case 1: .Offset(0, 1).Font.Color = vbBlack Case 2: .Offset(0, 1).Font.Color = vbRed Case 3: .Offset(0, 1).Font.Color = vbGreen Case 4: .Offset(0, 1).Font.Color = vbYellow Case 5: .Offset(0, 1).Font.Color = vbBlue Case 6: .Offset(0, 1).Font.Color = vbMagenta Case 7: .Offset(0, 1).Font.Color = vbCyan Case 8: .Offset(0, 1).Font.Color = vbWhite End Select End With Next iCell End Sub
The following GIF illustrates the effects of using the VBA font color based on value example macro.
Download the VBA Change Font Color Based on Cell Value Example Workbook
This Excel VBA Change Font Color Based on Cell Value Tutorial is accompanied by an Excel workbook with the data and VBA code I use when describing the step-by-step process above. Get this example workbook (for free) by clicking the button below.
The VBA code in the Excel workbook that accompanies this Excel VBA Change Font Color Based on Cell Value Tutorial is (always) stored in the Visual Basic Editor (VBE). If you don’t know how to work with the VBE, I suggest you read my Visual Basic Editor (VBE) Tutorial. I link to this Tutorial in the Related Excel Macro and VBA Training Materials and Resources Section above.
The following Excel Macro and VBA Tutorials may help you better understand and implement the contents above.
- Tutorials about general macro and VBA constructs and structures:
- Tutorials for Beginners:
- Excel Macros: Click here to open.
- Excel VBA: Click here to open.
- Enable macros in Excel: Click here to open.
- Work with the Visual Basic Editor (VBE): Click here to open.
- Create Sub procedures: Click here to open.
- Refer to objects (click here to open), including:
- Sheets: Click here to open.
- Cell ranges: Click here to open.
- Work with:
- Properties: Click here to open.
- Variables: Click here to open.
- Data types: Click here to open.
- Functions: Click here to open.
- Events: Click here to open.
- R1C1-style references: Click here to open.
- The Select Case statement: Click here to open.
- Loops: Click here to open.
- Tutorials for Beginners:
- Tutorials with practical VBA applications and macro examples:
- Activate a workbook: Click here to open.
- Find the last row and last column: Click here to open.
- Work with the Value property: Click here to open.
- Check if a cell is empty: Click here to open.
- Work with font characteristics: Click here to open.
- Work with Excel’s AutoFilter: Click here to open.
- Search and find: Click here to open.
This Excel VBA Change Font Color Based on Cell Value Tutorial is part of a more comprehensive series of Excel VBA Font Color Tutorials.
- Excel VBA Font Color Index in 2 Easy Steps: Click here to open.
- Excel VBA Font Color RGB in 2 Easy Steps: Click here to open.
- Excel VBA Font Color HEX in 5 Easy Steps: Click here to open.
- Excel VBA Change Font Color for Part of Text in 8 Easy Steps: Click here to open.
- Excel VBA Text Box Font Color in 2 Easy Steps: Click here to open.
- Excel VBA ActiveX Text Box Font Color in 2 Easy Steps: Click here to open.
- Excel VBA UserForm Text Box Font Color in 2 Easy Steps: Click here to open.
- Excel VBA Chart Data Label Font Color in 4 Easy Steps: Click here to open.
- Excel VBA ActiveX Label Font Color in 2 Easy Steps: Click here to open.
- Excel VBA UserForm Label Font Color in 2 Easy Steps: Click here to open.
You can find more Excel and VBA Tutorials in the organized Tutorials Archive: Click here to visit the Archives.
If you want to learn how to automate Excel (and save time) by working with macros and VBA, you may be interested in the following Premium Excel Macro and VBA Training Materials:
- Premium Courses at the Power Spreadsheets Academy: Click here to open.
- Books at the Power Spreadsheets Library: Click here to open.
- VBA Cheat Sheets: Click here to open.
If you want to save time when working with macros and VBA, you may be interested in AutoMacro: Click here to learn more about AutoMacro (affiliate link). AutoMacro is an add-in for VBA that installs directly into the VBE. Depending on the version, AutoMacro comes loaded with:
- Code generators.
- An extensive code library.
- The ability to create your own code library.
- Advanced coding tools.
If you need consulting services, you may want to consider working with ExcelRescue. ExcelRescue is my usual suggestion for people who (like you) may need help with Excel tasks/projects: Click here to visit ExcelRescue (affiliate link).
<<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
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>>
In this tutorial we’ll learn how to use Visual Basic for Applications (VBA) to modify text size and style in an Excel cell based on the cell content. This tutorial apply for Excel 365, 2021, 2019 and 2016.
Preliminaries
If you are new to Excel VBA development, I’ll recommend that before going through the tutorial you’ll look into our Excel VBA macro primer.
Before you start coding, you should enable your developer tab on Excel in the Ribbon, as otherwise you won’t be able to access your Visual Basic Editor.
Change your Excel cell text properties with VBA
Define your spreadsheet
We’ll start by defining an Excel spreadsheet that we will use as an example. Feel free to use it to follow along this tutorial.
- Open Microsoft Excel and create a new Macro Enabled Excel Workbook (.xlsm) named Excel_Macros.xlsm
- Save your Spreadsheet in your local drive.
- In the Sheet1 worksheet, go ahead and add the table below:
- Now, from the Ribbon, hit Formulas.
- Then hit Define Name.
- Define a Named Range on which you’ll apply your VBA code as shown below and hit OK.
Use Cell.Font VBA property to change font color and style
- Move to the Developer tab.
- Next go ahead and hit the Visual Basic button.
- In the left hand side Project Explorer, highlight the Excel_Macros.xlsm project then hit Insert and pick Module.
- A new VBA module named Module1 will be created.
- Go ahead and paste the following code in the newly created module:
Sub Color_Cell_Text_Condition()
Dim MyCell As Range
Dim StatValue As String
Dim StatusRange As Range
Set StatusRange = Range("Completion_Status")
'loop through all cells in the range
For Each MyCell In StatusRange
StatValue = MyCell.Value
'modify the cell text values as needed.
Select Case StatValue
'green
Case "Progressing"
With MyCell.Font
.Color = RGB(0, 255, 0)
.Size = 14
.Bold = True
End With
'orange
Case "Pending Feedback"
With MyCell.Font
.Color = RGB(255, 141, 0)
.Size = 14
.Bold = True
End With
'red
Case "Stuck"
With MyCell.Font
.Color = RGB(255, 0, 0)
.Size = 14
.Bold = True
End With
End Select
Next MyCell
End Sub
- Hit the Save button in your Visual Basic editor.
- Now hit Run and then pick Run Sub/UserForm (or simply hit F5).
- Move to your Sheet1 worksheet and notice the changes. Your table entries were assigned multiple color codes according to their text (using the RGB color function), and we also set the text to be bold and increase its size.
- If you haven’t saved your code, hit the Save button (or Ctrl+S), then also save your workbook.
Access your VBA Macro
- Note that your code is always available for you to run from the Macros command located in the View tab (or alternatively in Developer | Macros)