Форматирование текста в ячейке при помощи кода VBA Excel. Объект Font и его основные свойства. Примеры изменения начертания строк в заданном диапазоне.
В этой статье рассмотрены свойства шрифта (объекта Font), определяющие внешнее оформление (начертание) видимого значения ячейки. Это касается не только текста (строк), но и визуального начертания отображаемых дат и числовых значений.
Формат отображаемого значения
Когда мы из кода VBA Excel записываем в ячейку текстовое или другое значение, оно отображается в формате, присвоенном данной ячейке. Это может быть формат:
- рабочего листа по умолчанию;
- установленный для диапазона пользователем;
- примененный к диапазону из кода VBA Excel.
Если ячейка содержит текстовое значение, его начертание можно форматировать по отдельным частям (подстрокам). Такое форматирование доступно как в ручном режиме на рабочем листе, так и из кода VBA Excel.
У объекта Range есть свойство Font (шрифт), которое отвечает за форматирование (начертание) визуально отображаемого текста в ячейках рабочего листа. Его применение вызывает объект Font, который в свою очередь обладает собственным набором свойств, отвечающих за конкретный стиль начертания отображаемого значения.
Свойство | Описание | Значения |
---|---|---|
Name | наименование шрифта | «Arial», «Calibri», «Courier New», «Times New Roman» и т.д. |
Size | размер шрифта | от 1 до 409 пунктов |
Bold | полужирное начертание | True, False |
Italic | курсивное начертание | True, False |
FontStyle | заменяет Bold и Italic | «обычный», «полужирный», «курсив», «полужирный курсив» |
Superscript | надстрочный текст | True, False |
Subscript | подстрочный текст | True, False |
Underline | подчеркнутый текст | True, False |
Color* | цвет текста | от 0 до 16777215 |
*Color — это не единственное свойство, отвечающее за цвет отображаемого текста в ячейке. Оно также может принимать и другие значения, кроме указанных в таблице. Смотрите подробности в статьях Цвет текста (шрифта) в ячейке и Цвет ячейки (заливка, фон).
Примеры форматирования текста
Пример 1
В этом примере ячейкам диапазона «A1:A3» присвоим шрифты разных наименований:
Sub Primer1() Range(«A1»).Font.Name = «Courier» Range(«A1») = «Шрифт «Courier»» Range(«A2»).Font.Name = «Verdana» Range(«A2») = «Шрифт «Verdana»» Range(«A3»).Font.Name = «Times New Roman» Range(«A3») = «Шрифт «Times New Roman»» End Sub |
Пример 2
В этом примере рассмотрим применение одного свойства объекта Font к одной ячейке:
Sub Primer2() Range(«A5»).Font.Bold = True Range(«A5») = «Полужирное начертание» Range(«A6»).Font.FontStyle = «полужирный курсив» Range(«A6») = «Полужирный курсив» Range(«A7»).Font.Superscript = True Range(«A7») = «Надстрочное начертание» End Sub |
Пример 3
Форматирование диапазона из нескольких ячеек:
Sub Primer3() With Range(«A9:C11») .Value = «Форматируем диапазон» .Font.Underline = True .Font.Color = 75962 End With End Sub |
Пример 4
Пример форматирования шрифта в разных ячейках по одному свойству:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
Sub Primer4() Cells(1, 1) = «Свойство шрифта Bold = True» Cells(1, 1).Font.Bold = True Cells(2, 1) = «Свойство шрифта Color = xlGreen» Cells(2, 1).Font.Color = xlGreen Cells(3, 1) = «Свойство шрифта ColorIndex = 32» Cells(3, 1).Font.ColorIndex = 32 Cells(4, 1) = «Свойство шрифта FontStyle = ««Bold Italic»«» Cells(4, 1).Font.FontStyle = «Bold Italic» Cells(5, 1) = «Свойство шрифта Italic = True» Cells(5, 1).Font.Italic = True Cells(6, 1) = «Свойство шрифта Name = ««Courier New»«» Cells(6, 1).Font.Name = «Courier New» Cells(7, 1) = «Свойство шрифта Size = 14» Cells(7, 1).Font.Size = 14 Cells(8, 1) = «Свойство шрифта Subscript = True» Cells(8, 1).Font.Subscript = True Cells(9, 1) = «Свойство шрифта Superscript = True» Cells(9, 1).Font.Superscript = True Cells(10, 1) = «Свойство шрифта Underline = True» Cells(10, 1).Font.Underline = True End Sub |
The best way to draw a user’s attention to a cell or some text within a cell is to make it look different from the rest of the text.
One way to do this is to make the text bold, thereby highlighting it or stressing its importance.
The ‘Bold’ button in the Excel Home tab is of course everyone’s go-to way of making any text bold. A lot of people also like to use the keyboard shortcut CTRL+B.
However, you might need to make some text bold based on a certain condition, or only at the end of a calculation.
Unfortunately, there’s no Excel function that you can use to make text bold. But it is possible to do this using VBA.
In this tutorial, we will show you how to make text bold using VBA in a number of different use cases.
To make any text bold in VBA, we can use the Font.Bold property of a Range or Cell.
Let’s say you want to bold the text that is in cell A2 of your spreadsheet.
Here’s the code you can use to get this done:
Cells(1,2).Font.Bold=True
You can also use the Range function to accomplish the same:
Range("A2").Font.Bold = True
This will also work if you want to bold a whole range of cells, for example:
Range("A2:A8").Font.Bold = True
This will change cells in the range A1:A8 to bold.
Using the Visual Basic Immediate Window to Bold Text in Excel
You can use the Visual Basic developer’s Immediate Window to quickly run one-line VBA codes, such as the ones we discussed in the previous section.
To run the code in the Immediate Window, simply follow the steps shown below:
- From the Developer Menu Ribbon, select Visual Basic.
- Once your VBA window opens, your Immediate Window should be at the bottom. If you cannot see it, then Click View>Immediate Window or press CTRL+G on the keyboard.
- Paste your line of code in the Immediate Window and press the Return key.
When you get back to your Excel window, you should see the result of the executed code.
So if you used the line:
Range("A2:A8").Font.Bold = True
You should see all the cells in the range A2:A8 have the text converted to bold:
Writing a Visual Basic Module to Bold Text in Excel
If you prefer writing a VBA Module to bold the text instead, then you can enclose the same line of code within a Sub procedure as shown below:
Sub ConvertToBold()
Range("A1:A8").Font.Bold = True
End Sub
Here’s what you have to do in order to use the above procedure:
- From the Developer Menu Ribbon, select Visual Basic.
- Once your VBA window opens, Click Insert->Module and paste the above code in the Module window.
- To run the macro, go back to your Excel window and navigate to Developer->Macros.
- Select the name of the module, which is ConvertToBold in our example.
- Click Run.
You should find the cells in the range A2:A8 have the text converted to bold.
Some Practical Use-cases of the Font.Bold Property
Let us see some practical applications of the Font.Bold property.
How to Bold Selected Cells in Excel Using VBA
Let’s see a small module that can help you bold only the cells that you selected:
'Code by Steve from SpreadsheetPlanet.com Sub ConvertSelectedCellsToBold() Dim Rng As Range Dim myCell As Object Set Rng = Selection For Each myCell In Rng myCell.Font.Bold = True Next End Sub
To run the code do the following:
- Select the cells that you want to bold.
- Copy the above code to your Visual Basic module window.
- Run the macro.
- You should find the contents of all your selected cells converted to bold.
Explanation of the Code
In this code, we stored the selected range of cells in the variable Rng.
Then we used a for-loop to traverse over each cell (myCell) in the range, making the contents of each selected cell bold, using the line:
myCell.Font.Bold = True
How to Bold Cells Containing a Specific Text using VBA
Now consider a scenario where you need to highlight all the cells that contain a specific text using VBA.
This can be achieved by the following code:
'Code by Steve from SpreadsheetPlanet.com Sub ConvertCellsWithSpecificTextToBold() Dim Rng As Range Dim myCell As Object Dim myUnion As Range Set Rng = Selection searchString = InputBox("Please Enter the Search String") For Each myCell In Rng If InStr(myCell.Text, searchString) Then myCell.Font.Bold = True End If Next End Sub
To run the code do the following:
- Select the range of cells that you want to work with.
- Copy the above code to your Visual Basic module window.
- Run the macro.
- You will see a message window that asks you to enter your search string. Type your search string in the input box. In our example, we entered the word “King”.
- When you press the Return key, you should find all the cells that contain the word “King” highlighted in bold.
Explanation of the Code
In this code, we again stored the selected range of cells in the variable Rng. We used an InputBox to get the user’s search string input and we stored this text in the variable searchString.
We then used a for-loop to traverse over each cell (myCell) in the range and we checked if the cell contained the search string (using the InStr function). If it did, then we made the contents of the cell bold.
How to Find and Bold Specific Text in a Cell using VBA
Now, what if you only want to make the particular search string bold, instead of the entire cell?
For example, you might have a lot of data in your worksheet and you might want to bold only a particular word so that it stands out.
This can be achieved using the following module code:
'Code by Steve from SpreadsheetPlanet.com Sub ConvertSpecificTextToBold() Dim Rng As Range Dim myCell As Object Dim myUnion As Range Set Rng = Selection searchString = InputBox("Please Enter the Search String") For Each myCell In Rng If InStr(myCell.Text, searchString) Then myCell.Characters(WorksheetFunction.Find(searchString, myCell.Value), Len(searchString)).Font.Bold = True End If Next End Sub
To run the code do the following:
- Select the range of cells that you want to work with.
- Copy the above code to your Visual Basic module window.
- Run the macro.
- You will see a message window that asks you to enter your search string. Type your search string in the input box. In our example, we entered the word “King”.
- When you press the Return key, you should find only the word “King” highlighted in all your selected cells.
Explanation of the Code
In this code, we stored the selected range of cells in the variable Rng. We used an InputBox to get the user’s search string input and we stored this text in the variable searchString.
We then used a for-loop to traverse over each cell (myCell) in the range and we checked if the cell contained the search string.
If it did, then we used the WorksheetFunction.Find function to find the starting and ending position of the search string in the cell’s contents.
The WorksheetFunction object is used as a container for Excel worksheet functions that can be used in VBA.
So you can use the functions under this object the same way you would use regular functions in Excel. That means, the WorksheetFunction.Find function works the same way as Excel’s FIND function.
The Find function lets you find a search string in another given string and returns the position of the string in the cell’s contents. We used the function as follows:
WorksheetFunction.Find(searchString, myCell.Value)
This means “return the position of searchString in myCell.Value”. This gives the starting position of our search string. To get the ending position of the string we used the length of the search string itself (Len(searchString)).
We then used this information (starting and ending position of the search string) inside the Characters object.
The Characters object represents a range of characters within the cell (myCell). You can use this Characters object to format specific characters within the cell.
So you can set the Font.Bold property of the characters in your search string using the line:
myCell.Characters(WorksheetFunction.Find(searchString, myCell.Value), Len(searchString)).Font.Bold = True
Note: Once you change the font using VBA, you cannot undo the changes using the Undo button.
How to Remove the Bold.Font Setting in VBA
If you want to change the text font back by removing the bold setting, then all you need to do is set the Font.Bold property of the object to False.
In this tutorial, we saw how to bold text using VBA.
We showed you the basic syntax and then showed a few practical use cases where you might need to bold certain text in Excel using VBA.
We hope this was helpful and easy to follow.
Other Excel tutorials you may also like:
- How to Copy Formatting In Excel (4 Easy Ways)
- How to Flash an Excel Cell (Easy Step-by-Step Method)
- How to Auto Format Formulas in Excel (3 Easy Ways)
- How to Reverse a Text String in Excel (Using Formula & VBA)
- Highlight Cell If Value Exists in Another Column in Excel
- How to Set the Default Font in Excel (Windows and Mac)
- How to Add Bullet Points in Excel
- How to Rotate Text in Excel?
I have the following function inside my module.
Function Colorize(myValue)
ActiveCell.Select
Selection.Font.Bold = True
Colorize = myValue
End Function
The cell that will use this function should be turning bold — however, I get no error messages back and sad but true, its not turning bold. What am I missing?
Thanks
asked May 18, 2011 at 13:51
3
A UDF will only return a value it won’t allow you to change the properties of a cell/sheet/workbook. Move your code to a Worksheet_Change event or similar to change properties.
Eg
Private Sub worksheet_change(ByVal target As Range)
target.Font.Bold = True
End Sub
answered May 18, 2011 at 14:19
5
I use
chartRange = xlWorkSheet.Rows[1];
chartRange.Font.Bold = true;
to turn the first-row-cells-font into bold. And it works, and I am using also Excel 2007.
You can call in VBA directly
ActiveCell.Font.Bold = True
With this code I create a timestamp in the active cell, with bold font and yellow background
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
ActiveCell.Value = Now()
ActiveCell.Font.Bold = True
ActiveCell.Interior.ColorIndex = 6
End Sub
answered May 18, 2011 at 14:26
Return to VBA Code Examples
You can use VBA in order to make text in cells bold. In this tutorial, you will learn how to make text bold.
Bold Text With VBA
You would set the Font.Bold Property of the Font Object to True in order to make text in a cell bold. The following code will make the text in cell A1 bold:
Range("A1").Font.Bold = True
The result is:
The above example used the Range Object in conjunction with the Font Object. You can also use the Cell Object in conjunction with the Font Object in order to refer to the cell of interest. The following code will make the text in Cell C2 bold:
Cells(2, 3).Font.Bold = True
Clearing Bold With VBA
You would set the Font.Bold Property of the Font Object to False in order to make bold text in a cell the normal font weight. The following code will make bold text in cell A1, the normal font weight:
Range("a1").Font.Bold = False
Remove All Formatting With VBA
You can also remove all formatting from a single cell or cells in your worksheet including the bold font weight, using the .ClearFormats method. The following code will remove all formatting from all the cells in a worksheet and as a result, bold text will be changed into the normal font weight:
Cells.Select
Selection.ClearFormats
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!
Содержание
- VBA Cell Font – Change Color, Size, Style, & More
- VBA Cell Font
- Change Font Color
- vbColor
- Color – RGB
- ColorIndex
- Font Size
- VBA Coding Made Easy
- Bold Font
- Font Name
- Cell Style
- VBA Code Examples Add-in
- VBA Bold
- Bold Text With VBA
- Clearing Bold With VBA
- Remove All Formatting With VBA
- VBA Coding Made Easy
- VBA Code Examples Add-in
- VBA Excel. Форматирование текста в ячейке (объект Font)
- Формат отображаемого значения
- Основные свойства объекта Font
- Примеры форматирования текста
- 5 комментариев для “VBA Excel. Форматирование текста в ячейке (объект Font)”
- Excel VBA Font (Color, Size, Type, and Bold)
- Key Notes
- VBA Font Object
- Syntax
- VBA Font Color
- 1. Using Color Constants
- 2. Using RGB
- VBA Font Size
- VBA Font Name
- VBA Font Bold, Italic, and Underline
- Other Useful Font Properties
- Change Font to Bold in Excel VBA
- VBA Reference
- 120+ Project Management Templates
- Description:
- Change Font to Bold in Excel VBA – Solution:
- Change Font to Bold in Excel VBA – Examples:
VBA Cell Font – Change Color, Size, Style, & More
In this Article
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:
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:
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:
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:
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:
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!
Bold Font
or to clear Bold formatting:
Font Name
To change a font name use the Name property:
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:
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”:
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 Bold
In this Article
You can use VBA in order to make text in cells bold. In this tutorial, you will learn how to make text bold.
Bold Text With VBA
You would set the Font.Bold Property of the Font Object to True in order to make text in a cell bold. The following code will make the text in cell A1 bold:
The above example used the Range Object in conjunction with the Font Object. You can also use the Cell Object in conjunction with the Font Object in order to refer to the cell of interest. The following code will make the text in Cell C2 bold:
Clearing Bold With VBA
You would set the Font.Bold Property of the Font Object to False in order to make bold text in a cell the normal font weight. The following code will make bold text in cell A1, the normal font weight:
Remove All Formatting With VBA
You can also remove all formatting from a single cell or cells in your worksheet including the bold font weight, using the .ClearFormats method. The following code will remove all formatting from all the cells in a worksheet and as a result, bold text will be changed into the normal font weight:
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!
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. Форматирование текста в ячейке (объект Font)
Форматирование текста в ячейке при помощи кода VBA Excel. Объект Font и его основные свойства. Примеры изменения начертания строк в заданном диапазоне.
В этой статье рассмотрены свойства шрифта (объекта Font), определяющие внешнее оформление (начертание) видимого значения ячейки. Это касается не только текста (строк), но и визуального начертания отображаемых дат и числовых значений.
Формат отображаемого значения
Когда мы из кода VBA Excel записываем в ячейку текстовое или другое значение, оно отображается в формате, присвоенном данной ячейке. Это может быть формат:
- рабочего листа по умолчанию;
- установленный для диапазона пользователем;
- примененный к диапазону из кода VBA Excel.
Если ячейка содержит текстовое значение, его начертание можно форматировать по отдельным частям (подстрокам). Такое форматирование доступно как в ручном режиме на рабочем листе, так и из кода VBA Excel.
У объекта Range есть свойство Font (шрифт), которое отвечает за форматирование (начертание) визуально отображаемого текста в ячейках рабочего листа. Его применение вызывает объект Font, который в свою очередь обладает собственным набором свойств, отвечающих за конкретный стиль начертания отображаемого значения.
Основные свойства объекта Font
Свойство | Описание | Значения |
---|---|---|
Name | наименование шрифта | «Arial», «Calibri», «Courier New», «Times New Roman» и т.д. |
Size | размер шрифта | от 1 до 409 пунктов |
Bold | полужирное начертание | True, False |
Italic | курсивное начертание | True, False |
FontStyle | заменяет Bold и Italic | «обычный», «полужирный», «курсив», «полужирный курсив» |
Superscript | надстрочный текст | True, False |
Subscript | подстрочный текст | True, False |
Underline | подчеркнутый текст | True, False |
Color* | цвет текста | от 0 до 16777215 |
*Color — это не единственное свойство, отвечающее за цвет отображаемого текста в ячейке. Оно также может принимать и другие значения, кроме указанных в таблице. Смотрите подробности в статьях Цвет текста (шрифта) в ячейке и Цвет ячейки (заливка, фон).
Примеры форматирования текста
Пример 1
В этом примере ячейкам диапазона «A1:A3» присвоим шрифты разных наименований:
Пример 2
В этом примере рассмотрим применение одного свойства объекта Font к одной ячейке:
Пример 3
Форматирование диапазона из нескольких ячеек:
Пример 4
Пример форматирования шрифта в разных ячейках по одному свойству:
5 комментариев для “VBA Excel. Форматирование текста в ячейке (объект Font)”
Пример 2 не к одной ячейке, а к трём. Где пример к одной.
Добрый день, Алексей Леонидович!
Во втором примере показано применение одного свойства объекта Font к одной ячейке.
К ячейке «A5»:
Range(«A5»).Font.Bold = True
К ячейке «A6»:
Range(«A6»).Font.FontStyle = «полужирный курсив»
К ячейке «A7»:
Range(«A7»).Font.Superscript = True
Применение нескольких свойств объекта Font к одной ячейке может выглядеть следующим образом:
Скажите пожалуйста, а есть ли способ подставлять вместо свойства ячейки (Bold, Underline, Italic) переменную чтобы в цикле последовательно менять свойства ячейки одной командой? Это упрощенный пример, так сказать в принципе, есть ли способ записи типа .Cells(1,1).Font.Переменная=True где Переменная это одно из Bold, Italic, Underline?
With Worksheets(«Конфигурация»)
For i = 1 To 3
Select Case i
Case 1
s = «Bold»
Case 2
s = «Italic»
Case 3
s = «Underline»
End Select
.Cells(15, 1).Font.?s? = True
Next i
End With
Здравствуйте, Сергей!
Если заменить «Underline» на «Bold Italic» или «обычный» , тогда можно так:
С «Underline» такой фокус не проходит, но возвращает к обычному стилю.
нет, увы. Спасибо конечно, что мимо не прошли, но я дал лишь упрощенную формулировку задачи. На самом деле я хочу работать с объектами WMI, коих, как известно огромное количество и у каждого куча свойств. Я не хочу писать многокилометровый код и все время добавлять строки. Я хочу вынести на лист excel список объектов и слева от каждого в колонках список свойств. И в цикле пробегать по объектам и по внутреннему циклу по свойствам, подставлять все по очереди и получать значения. И для добавления еще одного мне нужно будет только добавить на лист объект или свойство. В код при этом лазить не нужно будет.
Но я уперся в это вот, нужно как-то подставлять в объект вместо свойства переменную. Для этого я и сделал этот крошечный пример. Здесь никто конечно не будет перебирать свойства в таком дурацком цикле, тем более, что свойства разные по формату, кому-то нужны цифры, кому-то булево значение. Так что этот пример смысла не имеет, но дает понять задачу.
Источник
Excel VBA Font (Color, Size, Type, and Bold)
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
To use it, first, you need to define the cell address, which you can specify in the following ways.
VBA Font Color
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:
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:
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:
If you want to apply font size to all cells in a worksheet you can use the following code:
And if only want to apply font size to cells where you have data, the code would be:
Or to the selected cell.
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:
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.
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).
Источник
Change Font to Bold in Excel VBA
VBA Reference
Effortlessly
Manage Your Projects
120+ Project Management Templates
Seamlessly manage your projects with our powerful & multi-purpose templates for project management.
120+ PM Templates Includes:
50+ Excel Templates
50+ PowerPoint Templates
25+ Word Templates
A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.
Save Up to 85% LIMITED TIME OFFER
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates
Excel Pack
50+ Excel PM Templates
PowerPoint Pack
50+ Excel PM Templates
MS Word Pack
25+ Word PM Templates
Ultimate Project Management Template
Ultimate Resource Management Template
Project Portfolio Management Templates
Description:
Some ties we need to change highlight the font to show its importance. We Change Font to Bold or change the background color or font color in Excel VBA, to highlight the text or some numbers. So that reader can easily recognize and look into that.
Change Font to Bold in Excel VBA – Solution:
We can change the font to Bold by using Font.Bold Property of a Range/Cell in Excel using VBA.
Change Font to Bold in Excel VBA – Examples:
The following examples will show you how to change the font to bold in Excel using VBA.
When we want to highlight some text in the Excel, we alsoe consider changing the Fornt and Background Colors. We use ColorIndex or RGB format of Colors to apply the color for both Font and Background . You can learn more here:
Also find related example to change font Color in Excel using VBA
In this topic we will see how change the font color in Excel VBA. Again, we change the font color in excel while generating the reports. We may want to highlight the font in red if the values are negative, in green if the values are positive. Or we may change font colors and sizes for headings. etc…
You can find multiple examples on changing the font colors in Excel using VBA
Find the related example to change the background color in Excel using VBA:
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.
You can find multiple examples on changing the Background colors in Excel using VBA.
A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.
Источник
In this article I will explain how you can use VBA to change the bold font property of cells and ranges. I have also provided an example on how to check if a cells has the bold font property on or off.
Jump To:
- Basics
- Example 1, Set Bold Property
- Example 2, Find Cells With Bold Font
You can download the code and file related to this article here.
–
Basics:
The following line of code makes the font in cell A1 bold:
Range("A1").Font.Bold = True
or
Range("A1").Font.FontStyle = "Bold"
Before:
After:
The following line of code removes the bold font property:
Range("A1").Font.Bold = False
or
Range("A1").Font.FontStyle = "Regular"
–
Example 1, Set Bold Property:
In this example there are a set of drop down lists in row 1. Each drop down list has the values “Yes” and “No”. For more information about creating drop down lists in Excel please see Excel VBA Drop Down Lists. If the user selects “Yes” the text in the cell under the drop down list will become bold. If the user selects “No” the bold font style from the cell below the drop down list will be removed. The “Yes”, “No” values for the drop down lists are in sheet 2:
The user can select “Yes” and “No” from the drop down lists:
The cell under the drop down list turns bold:
More bold font:
The program uses a worksheet_change event handler. The event handler executes when the user selects a value from the drop down lists:
'Executes when the user selects a new values from the drop down lists
Private Sub worksheet_change(ByVal target As Range)
Dim i As Integer
For i = 1 To 6
'checks if the Yes property has been selected
If Cells(1, i) = "Yes" Then
'changes the font to bold
Range(Cells(2, i), Cells(2, i)).Font.Bold = True
Else
'removes the bold font property
Range(Cells(2, i), Cells(2, i)).Font.Bold = False
End If
Next i
End Sub
The line below changes the font format to bold:
Range(Cells(2, i), Cells(2, i)).Font.Bold = True
The line below removes the bold font format:
Range(Cells(2, i), Cells(2, i)).Font.Bold = False
–
Example 2, Find Cells With Bold Font:
In this example when the user presses the Run button the program will loop through the cells in row 2. If the cell in row 2 has the bold font style the cell above in row 1 will be colored green :
In the figure below the bold font style was removed from cell C2 and the font style in cell B2 was changed to bold. After pressing the run button:
The code below executes when the user presses the run button:
'executes when the user presses the run button
Private Sub btnRun_Click()
Dim i As Integer
'loops through row 2
For i = 1 To 6
'checks if the font in the cell is bold
If Range(Cells(2, i), Cells(2, i)).Font.Bold = True Then
'changes the color of the cell in row 1 to green
Range(Cells(1, i), Cells(1, i)).Interior.Color = 3394611
Else
'removes any previous color applied to the content of the cell in row 1
Range(Cells(1, i), Cells(1, i)).Interior.Color = xlNone
End If
Next i
End Sub
The If statement below checks if the font in the cell is bold:
If Range(Cells(2, i), Cells(2, i)).Font.Bold = True Then
...
End If
The line below changes the color of the cell in row 1 to green. The number 3394611 is a color code. It was found using the macro recorder. For more information about using the macro recorder please see Excel VBA, Formatting Cells and Ranges Using the Macro Recorder:
Range(Cells(1, i), Cells(1, i)).Interior.Color = 3394611
The line below removes any previous coloring applied to the cell in row 1:
Range(Cells(1, i), Cells(1, i)).Interior.Color = xlNone
You can download the code and file related to this article here.
See also:
- VBA Excel, Italic Font
- VBA, Excel Font Formatting
- VBA, Excel Alignment
- Excel VBA, Formatting Cells and Ranges Using the Macro Recorder
If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website www.software-solutions-online.com
In this post, you’ll learn how to format a cell text and make the cell text bold in Excel VBA.
To Make Cell Text Bold in, you can use the .Bold command.
To run the VBA code,
- Under the Developer tab, Click on the Visual basics option.
- In the new tab, under the insert option click the module
- Enter the code and run it.
Bold Text With VBA
To make the text bold using the range method
Code:
Range("A1").Font.Bold = True
By cell method
Code:
Cells(2, 3).Font.Bold = True
Clear Bold Text
To clear bold text with VBA
Code:
Range("a1").Font.Bold = False
In this VBA Tutorial, you learn how to change or set the font characteristics of a cell range.
This VBA Font Tutorial is accompanied by Excel workbooks containing the data and macros I use in the examples below. You can get immediate free access to these example workbooks by subscribing to the Power Spreadsheets Newsletter.
Use the following Table of Contents to navigate to the section you’re interested in.
Related Excel VBA and Macro Tutorials
The following VBA and Macro Tutorials may help you better understand and implement the contents below:
- General VBA constructs and structures:
- Learn the basics of how to work with macros here.
- Learn about essential VBA terms here.
- Learn how to enable and disable macros here.
- Learn how to work with the Visual Basic Editor (VBE) here.
- Learn how to create object references here.
- Learn about the R1C1-style system here.
- Learn how to create Sub procedures here.
- Learn how to declare and work with variables here.
- Learn how to work with VBA data types here.
- Learn how to work with object properties here.
- Learn how to work with functions in VBA here.
- Learn how to work with loops here.
- Practical VBA applications and macro examples:
- Learn how to refer to worksheets here.
- Learn how to refer to cell ranges here.
- Learn how to find the last row in a worksheet here.
- Learn how to find the last column in a worksheet here.
- Learn how to specify a column’s width here.
- Learn how to identify empty cells here.
- Learn how to clear a cell here.
You can find additional VBA and Macro Tutorials in the Archives.
#1: Change or set font with theme fonts
VBA code to change or set font with theme fonts
To change or set the font by referring to the applicable theme fonts, use a statement with the following structure:
Range.Font.ThemeFont = xlThemeFontConstant
Process to change or set font with theme fonts
To change or set the font by referring to the applicable theme fonts, follow these steps:
- Identify the cell range whose font you modify (Range).
- Refer to the Font object representing Range’s font (Font).
- Set the Font.ThemeFont property to an xlThemeFont constant (Font.ThemeFont = xlThemeFontConstant), which specifies the theme font to be used.
VBA statement explanation
Item: Range
Range object representing the cell range whose font you modify.
You can usually work with, among others, the following properties to refer to this Range object:
- Worksheet.Range.
- Worksheet.Cells.
Item: Font
The Range.Font property returns a Font object representing Range’s font.
Item: ThemeFont
The Font.ThemeFont property sets the font by referring to the applicable theme fonts.
Item: =
The assignment operator assigns a new value (xlThemeFontConstant) to the Font.ThemeFont property.
Item: xlThemeFontConstant
The constants in the xlThemeFont enumeration specify the theme font. Therefore, set the Font.ThemeFont property to one of the following xlThemeFont constants:
xlThemeFont constant | Value | Description |
xlThemeFontMajor | 2 | Major theme font |
xlThemeFontMinor | 1 | Minor theme font |
xlThemeFontNone | 0 | Don’t use a theme font |
Macro example to change or set font with theme fonts
The following macro example sets the font in cell A5 (Range(“A5”)) of the “VBA Font” worksheet (Worksheets(“VBA Font”)) in the workbook where the macro is stored (ThisWorkbook) to the major theme font (font.ThemeFont = xlThemeFontMajor).
Sub fontThemeFont() 'Source: https://powerspreadsheets.com/ 'sets the font by referring to applicable theme fonts 'For further information: https://powerspreadsheets.com/excel-vba-font/ 'specify the theme font from the applied font scheme ThisWorkbook.Worksheets("VBA Font").Range("A5").font.ThemeFont = xlThemeFontMajor End Sub
Effects of executing macro example to change or set font with theme fonts
The following GIF illustrates the results of executing the macro example. As expected, Excel sets the font of cell A5 to the major theme font.
#2: Change or set font name
VBA code to change or set font name
To change or set the font name, use a statement with the following structure:
Range.Font.Name = "FontName"
Process to change or set font name
To change or set the font name, follow these steps:
- Identify the cell range whose font you name you change (Range).
- Refer to the Font object representing Range’s font (Font).
- Set the Font.Name property to a string specifying the font you use (Font.Name = “FontName”).
VBA statement explanation
Item: Range
Range object representing the cell range whose font name you change.
You can usually work with, among others, the following properties to refer to this Range object:
- Worksheet.Range.
- Worksheet.Cells.
Item: Font
The Range.Font property returns a Font object representing Range’s font.
Item: Name
The Font.Name property sets the font’s name.
Item: =
The assignment operator assigns a new value (“FontName”) to the Font.Name property.
Item: “FontName”
Set the Font.Name property to a string specifying the font you use (FontName).
If you explicitly declare a variable to represent “FontName”, work with the String data type.
Macro example to change or set font name
The following macro example sets the font in cell A6 (Range(“A6”)) of the “VBA Font” worksheet (Worksheets(“VBA Font”)) in the workbook where the macro is stored (ThisWorkbook) to Verdana (font.Name = “Verdana”).
Sub fontName() 'Source: https://powerspreadsheets.com/ 'sets the font 'For further information: https://powerspreadsheets.com/excel-vba-font/ 'specify the font name ThisWorkbook.Worksheets("VBA Font").Range("A6").font.Name = "Calibri" End Sub
Effects of executing macro example to change or set font name
The following GIF illustrates the results of executing the macro example. As expected, Excel sets the font of cell A6 to Verdana.
#3: Change or set font size
VBA code to change or set font size
To change or set the font size, use a statement with the following structure:
Range.Font.Size = FontSize#
Process to change or set font size
To change or set the font size, follow these steps:
- Identify the cell range whose font size you change (Range).
- Refer to the Font object representing Range’s font (Font).
- Set the Font.Size property to a number specifying the size (in points) of the font you use (Font.Size = FontSize#).
VBA statement explanation
Item: Range
Range object representing the cell range whose font size you change.
You can usually work with, among others, the following properties to refer to this Range object:
- Worksheet.Range.
- Worksheet.Cells.
Item: Font
The Range.Font property returns a Font object representing Range’s font.
Item: Size
The Font.Size property sets the font’s size.
Item: =
The assignment operator assigns a new value (FontSize#) to the Font.Size property.
Item: FontSize#
Set the Font.Size property to a number specifying the size (in points) of the font you use (FontSize#).
Macro example to change or set font size
The following macro example sets the font size of cell A7 (Range(“A7”)) of the “VBA Font” worksheet (Worksheets(“VBA Font”)) in the workbook where the macro is stored (ThisWorkbook) to 13 (font.Size = 13).
Sub fontSize() 'Source: https://powerspreadsheets.com/ 'sets the font size 'For further information: https://powerspreadsheets.com/excel-vba-font/ 'specify the font size ThisWorkbook.Worksheets("VBA Font").Range("A7").font.Size = 13 End Sub
Effects of executing macro example to change or set font size
The following GIF illustrates the results of executing the macro example. As expected, Excel sets the font size of cell A7 to 13.
#4: Change or set font style
VBA code to change or set font style
To change or set the font style, use a statement with the following structure:
Range.Font.FontStyle = "FontStyle"
Process to change or set font style
To change or set the font style, follow these steps:
- Identify the cell range whose font you style you change (Range).
- Refer to the Font object representing Range’s font (Font).
- Set the Font.Style property to a string specifying the font style you use (Font.FontStyle = “FontStyle”).
VBA statement explanation
Item: Range
Range object representing the cell range whose font style you change.
You can usually work with, among others, the following properties to refer to this Range object:
- Worksheet.Range.
- Worksheet.Cells.
Item: Font
The Range.Font property returns a Font object representing Range’s font.
Item: FontStyle
The Font.FontStyle property sets the font style.
Item: =
The assignment operator assigns a new value (“FontStyle”) to the Font.FontStyle property.
Item: “FontStyle”
Set the Font.FontStyle property to one of the following strings (FontStyle):
- Regular;
- Italic;
- Bold; or
- Bold Italic.
Macro example to change or set font style
The following macro example sets the font style of cell A8 (Range(“A8”)) of the “VBA Font” worksheet (Worksheets(“VBA Font”)) in the workbook where the macro is stored (ThisWorkbook) to bold and italic (font.fontStyle = “Bold Italic”).
Sub fontStyle() 'Source: https://powerspreadsheets.com/ 'sets the font style 'For further information: https://powerspreadsheets.com/excel-vba-font/ 'specify the font style ThisWorkbook.Worksheets("VBA Font").Range("A8").font.fontStyle = "Bold Italic" End Sub
Effects of executing macro example to change or set font style
The following GIF illustrates the results of executing the macro example. As expected, Excel sets the font style of cell A8 to bold and italic.
#5: Set font bold
VBA code to set font bold
To set the font to bold, use a statement with the following structure:
Range.Font.Bold = True
Process to set font bold
To set the font to bold, follow these steps:
- Identify the cell range whose font you set to bold (Range).
- Refer to the Font object representing Range’s font (Font).
- Set the Font.Bold property to True (Font.Bold = True).
VBA statement explanation
Item: Range
Range object representing the cell range whose font you set to bold.
You can usually work with, among others, the following properties to refer to this Range object:
- Worksheet.Range.
- Worksheet.Cells.
Item: Font
The Range.Font property returns a Font object representing Range’s font.
Item: Bold
The Font.Bold property sets the font to bold (or not bold).
Item: =
The assignment operator assigns a new value (True) to the Font.Bold property.
Item: True
To make the font bold, set the Font.Bold property to True.
To remove the font’s bold formatting, set the Font.Bold property to False.
Macro example to set font bold
The following macro example makes the font of cell A9 (Range(“A9”)) of the “VBA Font” worksheet (Worksheets(“VBA Font”)) in the workbook where the macro is stored (ThisWorkbook) bold (font.Bold = True).
Sub fontBold() 'Source: https://powerspreadsheets.com/ 'sets font to bold 'For further information: https://powerspreadsheets.com/excel-vba-font/ 'make font bold ThisWorkbook.Worksheets("VBA Font").Range("A9").font.Bold = True End Sub
Effects of executing macro example to set font bold
The following GIF illustrates the results of executing the macro example. As expected, Excel makes the font of cell A9 bold.
#6: Set font italic
VBA code to set font italic
To set the font to italic, use a statement with the following structure:
Range.Font.Italic = True
Process to set font italic
To set the font to italic, follow these steps:
- Identify the cell range whose font you set to italic (Range).
- Refer to the Font object representing Range’s font (Font).
- Set the Font.Italic property to True (Font.Italic = True).
VBA statement explanation
Item: Range
Range object representing the cell range whose font you set to italic.
You can usually work with, among others, the following properties to refer to this Range object:
- Worksheet.Range.
- Worksheet.Cells.
Item: Font
The Range.Font property returns a Font object representing Range’s font.
Item: Italic
The Font.Italic property sets the font to italic (or not italic).
Item: =
The assignment operator assigns a new value (True) to the Font.Italic property.
Item: True
To make the font italic, set the Font.Italic property to True.
To remove the font’s italic formatting, set the Font.Bold property to False.
Macro example to set font italic
The following macro example makes the font of cell A10 (Range(“A10”)) of the “VBA Font” worksheet (Worksheets(“VBA Font”)) in the workbook where the macro is stored (ThisWorkbook) italic (font.Italic = True).
Sub fontItalic() 'Source: https://powerspreadsheets.com/ 'sets font style to italic 'For further information: https://powerspreadsheets.com/excel-vba-font/ 'make font italic ThisWorkbook.Worksheets("VBA Font").Range("A10").font.Italic = True End Sub
Effects of executing macro example to set font italic
The following GIF illustrates the results of executing the macro example. As expected, Excel makes the font of cell A10 italic.
#7: Set font underline
VBA code to set font underline
To underline the font, use a statement with the following structure:
Range.Font.Underline = xlUnderlineStyleConstant
Process to set font underline
To underline the font, follow these steps:
- Identify the cell range whose font you underline (Range).
- Refer to the Font object representing Range’s font (Font).
- Set the Font.Underline property to an xlUnderlineStyle constant (Font.Underline = xlUnderlineStyleConstant), which specifies the type of font underline.
VBA statement explanation
Item: Range
Range object representing the cell range whose font you underline.
You can usually work with, among others, the following properties to refer to this Range object:
- Worksheet.Range.
- Worksheet.Cells.
Item: Font
The Range.Font property returns a Font object representing Range’s font.
Item: Underline
The Font.Underline property sets the type of font underline.
Item: =
The assignment operator assigns a new value (xlUnderlineStyleConstant) to the Font.Underline property.
Item: xlUnderlineStyleConstant
The constants in the xlUnderlineStyle enumeration specify the type of font underline. Therefore, set the Font.Underline property to one of the following xlUnderlineStyle constants:
xlUnderlineStyle constant | Value |
xlUnderlineStyleDouble | -4119 |
xlUnderlineStyleDoubleAccounting | 5 |
xlUnderlineStyleNone | -4142 |
xlUnderlineStyleSingle | 2 |
xlUnderlineStyleSingleAccounting | 4 |
Macro example to set font underline
The following macro example underlines with a double line (font.Underline = xlUnderlineStyleDouble) the font of cell A11 (Range(“A11”)) of the “VBA Font” worksheet (Worksheets(“VBA Font”)) in the workbook where the macro is stored (ThisWorkbook).
Sub fontUnderline() 'Source: https://powerspreadsheets.com/ 'underlines the font 'For further information: https://powerspreadsheets.com/excel-vba-font/ 'underline the font ThisWorkbook.Worksheets("VBA Font").Range("A11").font.Underline = xlUnderlineStyleDouble End Sub
Effects of executing macro example to set font underline
The following GIF illustrates the results of executing the macro example. As expected, Excel underlines the font of cell A11 with a double line.
#8: Set font strikethrough
VBA code to set font strikethrough
To strike the font through, use a statement with the following structure:
Range.Font.Strikethrough = True
Process to set font strikethrough
To strike the font through, follow these steps:
- Identify the cell range whose font you strike through (Range).
- Refer to the Font object representing Range’s font (Font).
- Set the Font.Strikethrough property to True (Font.Strikethrough = True).
VBA statement explanation
Item: Range
Range object representing the cell range whose font you strike through.
You can usually work with, among others, the following properties to refer to this Range object:
- Worksheet.Range.
- Worksheet.Cells.
Item: Font
The Range.Font property returns a Font object representing Range’s font.
Item: Strikethrough
The Font.Strikethrough property strikes through (or not) the font with a horizontal line.
Item: =
The assignment operator assigns a new value (True) to the Font.Strikethrough property.
Item: True
To strike through the font with a horizontal line, set the Font.Strikethrough property to True.
To remove a font’s strike through horizontal line, set the Font.Strikethrough property to False.
Macro example to set font strikethrough
The following macro example strikes through (font.Strikethrough = True) the font of cell A12 (Range(“A12”)) of the “VBA Font” worksheet (Worksheets(“VBA Font”)) in the workbook where the macro is stored (ThisWorkbook).
Sub fontStrikethrough() 'Source: https://powerspreadsheets.com/ 'strikes font through 'For further information: https://powerspreadsheets.com/excel-vba-font/ 'strike through font ThisWorkbook.Worksheets("VBA Font").Range("A12").font.Strikethrough = True End Sub
Effects of executing macro example to set font strikethrough
The following GIF illustrates the results of executing the macro example. As expected, Excel strikes the font of cell A12 through.
#9: Change or set font color with RGB color model
VBA code to change or set font color with RGB color model
To change or set the font color with the RGB color model, use a statement with the following structure:
Range.Font.Color = RGB(Red, Green, Blue)
Process to change or set font color with RGB color model
To change or set the font color with the RGB color model, follow these steps:
- Identify the cell range whose font color you change with the RGB color model (Range).
- Refer to the Font object representing Range’s font (Font).
- Specify the red, green and blue components of the color with the RGB function (RGB(Red, Green, Blue)).
- Set the Font.Color property to the value returned by the RGB Function (Font.Color = RGB(Red, Green, Blue)).
VBA statement explanation
Item: Range
Range object representing the cell range whose font color you change with the RGB color model.
You can usually work with, among others, the following properties to refer to this Range object:
- Worksheet.Range.
- Worksheet.Cells.
Item: Font
The Range.Font property returns a Font object representing Range’s font.
Item: Color
The Font.Color property sets the font color using a numeric value.
Item: =
The assignment operator assigns a new value (returned by the RGB function) to the Font.Color property.
Item: RGB(Red, Green, Blue)
Theoretically, you can set the Font.Color property to a value specifying the font color you use.
In practice, you can use the RGB function to obtain the value specifying the font color. For these purposes, specify the Red, Green and Blue components of the color.
When working with the RGB function, consider the following:
- Specify each component (Red, Green and Blue) as numbers between 0 and 255 (inclusive).
- If you use a value exceeding 255, VBA assumes that the value is 255.
Macro example to change or set font color with RGB color model
The following macro example sets the font color of cell A13 (Range(“A13”)) of the “VBA Font” worksheet (Worksheets(“VBA Font”)) in the workbook where the macro is stored (ThisWorkbook) to red with the RGB color model (font.Color = RGB(255, 0, 0)).
Sub fontColorRgb() 'Source: https://powerspreadsheets.com/ 'sets font color using RGB color model 'For further information: https://powerspreadsheets.com/excel-vba-font/ 'specify font color with RGB function ThisWorkbook.Worksheets("VBA Font").Range("A13").font.Color = RGB(255, 0, 0) End Sub
Effects of executing macro example to change or set font color with RGB color model
The following GIF illustrates the results of executing the macro example. As expected, Excel sets the font color of cell A13 to red with the RGB color model.
#10: Change or set font color with color index (ColorIndex)
VBA code to change or set font color with color index (ColorIndex)
To change or set the font color with the ColorIndex property, use a statement with the following structure:
Range.Font.ColorIndex = ColorIndex#
Process to change or set font color with color index (ColorIndex)
To change or set the font color with the ColorIndex property, follow these steps:
- Identify the cell range whose font color you change with the ColorIndex property (Range).
- Refer to the Font object representing Range’s font (Font).
- Set the Font.ColorIndex property to a value between 0 and 56 or an xlColorIndex constant (Font.ColorIndex = ColorIndex#).
VBA statement explanation
Item: Range
Range object representing the cell range whose font color you change with the ColorIndex property.
You can usually work with, among others, the following properties to refer to this Range object:
- Worksheet.Range.
- Worksheet.Cells.
Item: Font
The Range.Font property returns a Font object representing Range’s font.
Item: ColorIndex
The Font.ColorIndex property sets the font color using the current color palette or a constant from the xlColorIndex enumeration.
Item: =
The assignment operator assigns a new value (ColorIndex#) to the Font.ColorIndex property.
Item: ColorIndex#
Set the Font.ColorIndex to one of the following:
- A value between 0 and 56, representing a color from the current color palette.
- One of the following xlColorIndex constants:
- xlColorIndexAutomatic (-4105), which represents automatic color.
- xlColorIndexNone (-4142), which represents no color.
Macro example to change or set font color with color index (ColorIndex)
The following macro example sets the font color of cell A14 (Range(“A14”)) of the “VBA Font” worksheet (Worksheets(“VBA Font”)) in the workbook where the macro is stored (ThisWorkbook) to blue with the ColorIndex property (font.ColorIndex = 5).
Sub fontColorIndex() 'Source: https://powerspreadsheets.com/ 'sets the font color by referring to the current color palette or a constant 'For further information: https://powerspreadsheets.com/excel-vba-font/ 'specify font color as index value of the current color palette or an XlColorIndex constant ThisWorkbook.Worksheets("VBA Font").Range("A14").font.ColorIndex = 5 End Sub
Effects of executing macro example to change or set font color with color index (ColorIndex)
The following GIF illustrates the results of executing the macro example. As expected, Excel sets the font color of cell A14 to blue with the ColorIndex property.
#11: Set font color to Automatic
VBA code to set font color to Automatic
To set the font color to Automatic (within the color palette), use a statement with the following structure:
Range.Font.ColorIndex = xlColorIndexAutomatic
Process to set font color to Automatic
To set the font color to Automatic (within the color palette), follow these steps:
- Identify the cell range whose font color you set to Automatic (Range).
- Refer to the Font object representing Range’s font (Font).
- Set the Font.ColorIndex property to xlColorIndexAutomatic (Font.ColorIndex = xlColorIndexAutomatic).
VBA statement explanation
Item: Range
Range object representing the cell range whose font color you set to Automatic (within the color palette).
You can usually work with, among others, the following properties to refer to this Range object:
- Worksheet.Range.
- Worksheet.Cells.
Item: Font
The Range.Font property returns a Font object representing Range’s font.
Item: ColorIndex
The Font.ColorIndex property sets the font color using the current color palette or a constant from the xlColorIndex enumeration.
Item: =
The assignment operator assigns a new value (xlColorIndexAutomatic) to the Font.ColorIndex property.
Item: xlColorIndexAutomatic
To set the font color to Automatic, set the Font.ColorIndex to:
- xlColorIndexAutomatic (-4105); or
- 0.
Macro example to set font color to Automatic
The following macro example sets the font color of cell A15 (Range(“A15”)) of the “VBA Font” worksheet (Worksheets(“VBA Font”)) in the workbook where the macro is stored (ThisWorkbook) to Automatic (font.ColorIndex = xlColorIndexAutomatic).
Sub fontColorAutomatic() 'Source: https://powerspreadsheets.com/ 'sets the font color to automatic 'For further information: https://powerspreadsheets.com/excel-vba-font/ 'specify the font color as Automatic ThisWorkbook.Worksheets("VBA Font").Range("A15").font.ColorIndex = xlColorIndexAutomatic End Sub
Effects of executing macro example to set font color to Automatic
The following GIF illustrates the results of executing the macro example. As expected, Excel sets the font color of cell A15 to Automatic (from blue).
#12: Change or set font color with theme color scheme (ThemeColor, xlThemeColorAccent)
VBA code to change or set font color with theme color scheme (ThemeColor, xlThemeColorAccent)
To change or set the font color with the theme color scheme, use a statement with the following structure:
Range.Font.ThemeColor = xlThemeColorConstant
Process to change or set font color with theme color scheme (ThemeColor, xlThemeColorAccent)
To change or set the font color with the theme color scheme, follow these steps:
- Identify the cell range whose font color you change with the theme color scheme (Range).
- Refer to the Font object representing Range’s font (Font).
- Set the Font.ThemeColor property to an xlThemeColor constant (Font.ThemeColor = xlThemeColorConstant).
VBA statement explanation
Item: Range
Range object representing the cell range whose font color you change with the theme color scheme.
You can usually work with, among others, the following properties to refer to this Range object:
- Worksheet.Range.
- Worksheet.Cells.
Item: Font
The Range.Font property returns a Font object representing Range’s font.
Item: ThemeColor
The Font.ThemeColor property sets the font color using the theme color scheme.
Item: =
The assignment operator assigns a new value (xlThemeColorConstant) to the Font.ThemeColor property.
Item: xlThemeColorConstant
The constants in the xlThemeColor enumeration specify the theme color. Therefore, set the Font.ThemeColor property to one of the following xlThemeColor constants:
xlThemeColor constant | Value | Description |
xlThemeColorAccent1 | 5 | Accent 1. |
xlThemeColorAccent2 | 6 | Accent 2. |
xlThemeColorAccent3 | 7 | Accent 3. |
xlThemeColorAccent4 | 8 | Accent 4. |
xlThemeColorAccent5 | 9 | Accent 5. |
xlThemeColorAccent6 | 10 | Accent 6. |
xlThemeColorDark1 | 1 | Dark 1. |
xlThemeColorDark2 | 3 | Dark 2. |
xlThemeColorFollowedHyperlink | 12 | Followed hyperlink. |
xlThemeColorHyperlink | 11 | Hyperlink. |
xlThemeColorLight1 | 2 | Light 1. |
xlThemeColorLight2 | 4 | Light 2. |
Macro example to change or set font color with theme color scheme (ThemeColor, xlThemeColorAccent)
The following macro example sets the font color of cell A16 (Range(“A16”)) of the “VBA Font” worksheet (Worksheets(“VBA Font”)) in the workbook where the macro is stored (ThisWorkbook) to the accent 1 of the theme color (font.ThemeColor = xlThemeColorAccent1).
Sub fontThemeColor() 'Source: https://powerspreadsheets.com/ 'sets font color by referring to applicable theme colors 'For further information: https://powerspreadsheets.com/excel-vba-font/ 'specify the font color from the theme color scheme ThisWorkbook.Worksheets("VBA Font").Range("A16").font.ThemeColor = xlThemeColorAccent1 End Sub
Effects of executing macro example to change or set font color with theme color scheme (ThemeColor, xlThemeColorAccent)
The following GIF illustrates the results of executing the macro example. As expected, Excel sets the font color of cell A16 to the accent 1 of the theme color.
#13: Change or set font tint and shade
VBA code to change or set font tint and shade
To change or set the font tint and shade, use a statement with the following structure:
Range.Font.TintAndShade = TintAndShade#
Process to change or set font tint and shade
To change or set the font tint and shade, follow these steps:
- Identify the cell range whose font tint and shade you change (Range).
- Refer to the Font object representing Range’s font (Font).
- Set the Font.TintAndShade property to a value (Font.TintAndShade = TintAndShade#) between -1 (darkest shade) and 1 (lightest shade).
VBA statement explanation
Item: Range
Range object representing the cell range whose font tint and shade you change.
You can usually work with, among others, the following properties to refer to this Range object:
- Worksheet.Range.
- Worksheet.Cells.
Item: Font
The Range.Font property returns a Font object representing Range’s font.
Item: TintAndShade
The Font.TintAndShade property lightens or darkens the font color.
Item: =
The assignment operator assigns a new value (TintAndShade#) to the Font.TintAndShade property.
Item: TintAndShade#
Set the Font.TintAndShade property to a value between -1 (darkest shade) and 1 (lightest shade). If you attempt to set the Font.TintAndShade property to a value outside this range, a run-time error (5: Invalid procedure call or argument) occurs.
Macro example to change or set font tint and shade
The following macro example lightens the font (font.TintAndShade = 0.5) of cell A17 (Range(“A17”)) of the “VBA Font” worksheet (Worksheets(“VBA Font”)) in the workbook where the macro is stored (ThisWorkbook).
Sub fontTintAndShade() 'Source: https://powerspreadsheets.com/ 'lightens or darkens the font color 'For further information: https://powerspreadsheets.com/excel-vba-font/ 'lighten or darken the font color ThisWorkbook.Worksheets("VBA Font").Range("A17").font.TintAndShade = 0.5 End Sub
Effects of executing macro example to change or set font tint and shade
The following GIF illustrates the results of executing the macro example. As expected, Excel lightens the font color of cell A17.
#14: Set font subscript
VBA code to set font subscript
To format the font as subscript, use a statement with the following structure:
Range.Font.Subscript = True
Process to set font subscript
To format the font as subscript, follow these steps:
- Identify the cell range whose font you format as subscript (Range).
- Refer to the Font object representing Range’s font (Font).
- Set the Font.Subscript property to True (Font.Subscript = True).
VBA statement explanation
Item: Range
Range object representing the cell range whose font you format as subscript.
You can usually work with, among others, the following properties to refer to this Range object:
- Worksheet.Range.
- Worksheet.Cells.
Item: Font
The Range.Font property returns a Font object representing Range’s font.
Item: Subscript
The Font.Subscript property formats the font as subscript (or not).
Item: =
The assignment operator assigns a new value (True) to the Font.Subscript property.
Item: True
To format the font as subscript, set the Font.Subscript property to True.
To remove the font’s subscript formatting, set the Font.Subscript property to False.
Macro example to set font subscript
The following macro example formats the font of cell A18 (Range(“A18”)) of the “VBA Font” worksheet (Worksheets(“VBA Font”)) in the workbook where the macro is stored (ThisWorkbook) as subscript (font.Subscript = True).
Sub fontSubscript() 'Source: https://powerspreadsheets.com/ 'formats the font as a subscript 'For further information: https://powerspreadsheets.com/excel-vba-font/ 'format the font as subscript ThisWorkbook.Worksheets("VBA Font").Range("A18").font.Subscript = True End Sub
Effects of executing macro example to set font subscript
The following GIF illustrates the results of executing the macro example. As expected, Excel formats the font of cell A18 as subscript.
#15: Set font superscript
VBA code to set font superscript
To format the font as superscript, use a statement with the following structure:
Range.Font.Superscript = True
Process to set font superscript
To format the font as superscript, follow these steps:
- Identify the cell range whose font you format as superscript (Range).
- Refer to the Font object representing Range’s font (Font).
- Set the Font.Superscript property to True (Font.Superscript = True).
VBA statement explanation
Item: Range
Range object representing the cell range whose font you format as superscript.
You can usually work with, among others, the following properties to refer to this Range object:
- Worksheet.Range.
- Worksheet.Cells.
Item: Font
The Range.Font property returns a Font object representing Range’s font.
Item: Superscript
The Font.Superscript property formats the font as superscript (or not).
Item: =
The assignment operator assigns a new value (True) to the Font.SuperScript property.
Item: True
To format the font as superscript, set the Font.Superscript to True.
To remove the font’s superscript formatting, set the Font.Superscript to False.
Macro example to set font superscript
The following macro example formats the font of cell A19 (Range(“A19”)) of the “VBA Font” worksheet (Worksheets(“VBA Font”)) in the workbook where the macro is stored (ThisWorkbook) as superscript (font.Superscript = True).
Sub fontSuperscript() 'Source: https://powerspreadsheets.com/ 'formats the font as a superscript 'For further information: https://powerspreadsheets.com/excel-vba-font/ 'format the font as superscript ThisWorkbook.Worksheets("VBA Font").Range("A19").font.Superscript = True End Sub
Effects of executing macro example to set font superscript
The following GIF illustrates the results of executing the macro example. As expected, Excel formats the font of cell A19 as superscript.
Learn more about specifying font characteristics with VBA
Workbook examples used in this VBA Font Tutorial
You can get immediate free access to the example workbooks that accompany this VBA Font Tutorial by subscribing to the Power Spreadsheets Newsletter.
References to constructs used in this VBA Font Tutorial
Use the following links to visit the appropriate webpage in the Microsoft Developer Network:
- Refer to the workbook containing the cell range you work with:
- Workbook object.
- Application.ThisWorkbook property.
- Refer to the worksheet containing the cell range you work with:
- Worksheet object.
- Workbook.Worksheets property.
- Refer to the cell range you work with:
- Range object.
- Worksheet.Range property.
- Refer to a cell range’s font:
- Font object.
- Range.Font property.
- Set or change a font’s properties:
- Font.Bold property.
- Font.Color property.
- Font.ColorIndex property and xlColorIndex enumeration.
- Font.FontStyle property.
- Font.Italic property.
- Font.Name property.
- Font.Size property.
- Font.Strikethrough property.
- Font.Subscript property.
- Font.Superscript property.
- Font.ThemeColor property and xlThemeColor enumeration.
- Font.ThemeFont property and xlThemeFont enumeration.
- Font.TintAndShade property.
- Font.Underline property and xlUnderlineStyle enumeration.
- Assign a new value to a property:
- = operator.
- Obtain a color with the RGB color model:
- RGB function.
- Work with variables and data types:
- Boolean data type.
- String data type.
Change Font to Bold in Excel VBA
Description:
Some ties we need to change highlight the font to show its importance. We Change Font to Bold or change the background color or font color in Excel VBA, to highlight the text or some numbers. So that reader can easily recognize and look into that.
Change Font to Bold in Excel VBA – Solution:
We can change the font to Bold by using Font.Bold Property of a Range/Cell in Excel using VBA.
Change Font to Bold in Excel VBA – Examples:
The following examples will show you how to change the font to bold in Excel using VBA.
'In this Example I am changing the Range B4 Font to Bold Sub sbChangeFontToBold() 'Using Cell Object Cells(4, 2).Font.Bold = True 'Using Range Object Range("B4").Font.Bold = True End Sub
When we want to highlight some text in the Excel, we alsoe consider changing the Fornt and Background Colors. We use ColorIndex or RGB format of Colors to apply the color for both Font and Background . You can learn more here:
Also find related example to change font Color in Excel using VBA
In this topic we will see how change the font color in Excel VBA. Again, we change the font color in excel while generating the reports. We may want to highlight the font in red if the values are negative, in green if the values are positive. Or we may change font colors and sizes for headings. etc…
You can find multiple examples on changing the font colors in Excel using VBA
Find the related example to change the background color in Excel using VBA:
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.
You can find multiple examples on changing the Background colors in Excel using VBA.
A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.
Save Up to 85% LIMITED TIME OFFER
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates
Excel Pack
50+ Excel PM Templates
PowerPoint Pack
50+ Excel PM Templates
MS Word Pack
25+ Word PM Templates
Ultimate Project Management Template
Ultimate Resource Management Template
Project Portfolio Management Templates
Related Posts
-
- Description:
- Change Font to Bold in Excel VBA – Solution:
- Change Font to Bold in Excel VBA – Examples:
VBA Reference
Effortlessly
Manage Your Projects
120+ Project Management Templates
Seamlessly manage your projects with our powerful & multi-purpose templates for project management.
120+ PM Templates Includes:
Effectively Manage Your
Projects and Resources
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.
Page load link
Go to Top