Vba excel выделить текст жирным

Форматирование текста в ячейке при помощи кода 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.

Dataset with text to bold

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
Specified cell font is bold

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.

All cells in the specified range are 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:

  1. From the Developer Menu Ribbon, select Visual Basic.
Click on Developer tab and then on Visual basic
  1. 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.
Click on Immediate window
  1. Paste your line of code in the Immediate Window and press the Return key.
Enter the code in the immediate window

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:

All cells in the specified range are 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:

  1. From the Developer Menu Ribbon, select Visual Basic.
  2. Once your VBA window opens, Click Insert->Module and paste the above code in the Module window.
Click on Module
  1. To run the macro, go back to your Excel window and navigate to Developer->Macros.
Click on Developer tab and then click on Macros
  1. Select the name of the module, which is ConvertToBold in our example.
Select the Macro you want to run
  1. 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:

  1. Select the cells that you want to bold.
Select the cells you want to bold
  1. Copy the above code to your Visual Basic module window.
  2. Run the macro.
  3. You should find the contents of all your selected cells converted to bold.
Selected cells are 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:

  1. Select the range of cells that you want to work with. 
  2. Copy the above code to your Visual Basic module window.
  3. Run the macro.
  4. 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”.
enter the word you want to bold in the input box
  1. When you press the Return key, you should find all the cells that contain the word “King” highlighted in bold.
Cells with the word King are 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:

  1. Select the range of cells that you want to work with. 
  2. Copy the above code to your Visual Basic module window.
  3. Run the macro.
  4. 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”.
Enter the word you want to bold
  1. When you press the Return key, you should find only the word “King” highlighted in all your selected cells.
Only the word gets highlighted

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?

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:

  1. vbBlack: Black
  2. vbRed: Red
  3. vbGreen: Green
  4. vbYellow: Yellow
  5. vbBlue: Blue
  6. vbMagenta: Magenta
  7. vbCyan: Cyan
  8. 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

    I want to set bold some text in string.How can i do it ?

    ashleedawg's user avatar

    ashleedawg

    20k8 gold badges73 silver badges104 bronze badges

    asked Jul 25, 2012 at 7:20

    Mennan's user avatar

    By using Characters.

    Range("A1").Characters(8, 5).Font.Bold = True
    

    answered Jul 25, 2012 at 7:26

    GSerg's user avatar

    GSergGSerg

    75.3k17 gold badges160 silver badges340 bronze badges

    1

    I would say use this dynamic formula —

    Range("A1").Characters(worksheetfunction.find("Excel",Range("A1").value,1),len("Excel")).font.bold = True
    

    answered Oct 1, 2013 at 11:55

    anish's user avatar

    anishanish

    611 silver badge1 bronze badge

    Another way for people who need a quick fix and aren’t comfortable using VBA:

    1. Copy and paste the cell range into a word document (it will look messy at first).
    2. Go to «replace» (top right).
    3. Type the word you want to make bold into the «Find what:» field and the same into the «Replace with:» field, then when you are on the «Replace With:» box press CTRL B. You should see «Format: Font: Bold» appear beneath it.
    4. Click Replace All and you should see all the targeted words go bold.
    5. Hover over your Excel text (currently in Word) and you should see a small symbol of 4 arrows appear at the top left of the text. Click that to highlight the cells, then you can copy them and paste back into excel.

    Not the fastest way but if you’re not familiar with VBA and need a quick fix this will work for you!

    Not just for Bold:
    CTRL I for italics, CTRL U for underlined.

    answered Nov 2, 2015 at 12:25

    ChaPPer5's user avatar

    ChaPPer5ChaPPer5

    951 silver badge8 bronze badges

    Try this if you need to bold multiple specific text:

    Sub Find_and_Bold()
    Dim rCell As Range, sToFind As String, iSeek As Long
    Dim Text(1 To 4) As String
    Dim i As Integer
    
    
    Text(1) = "text1"
    Text(2) = "text2"
    Text(3) = "text3"
    Text(4) = "text4"
    
    
    For Each rCell In Range("C7:C1000")
        For i = LBound(Text) To UBound(Text)
                sToFind = Text(i)
                iSeek = InStr(1, rCell.Value, sToFind)
            Do While iSeek > 0
                rCell.Characters(iSeek, Len(sToFind)).Font.Bold = True
                iSeek = InStr(iSeek + 1, rCell.Value, sToFind)
            Loop
        Next i
    Next rCell
    
    End Sub
    

    The source for this solution is from: http://www.vbaexpress.com/forum/showthread.php?52245-Make-specific-text-bold-in-cells

    answered Jul 24, 2021 at 15:59

    Natan C's user avatar

    title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

    Font.Bold property (Excel)

    vbaxl10.chm559074

    vbaxl10.chm559074

    excel

    Excel.Font.Bold

    7343989f-f973-0b1d-e595-c625ef2e0c15

    04/26/2019

    medium

    Font.Bold property (Excel)

    True if the font is bold. Read/write Variant.

    Syntax

    expression.Bold

    expression A variable that represents a Font object.

    Example

    This example sets the font to bold for the range A1:A5 on Sheet1.

    Worksheets("Sheet1").Range("A1:A5").Font.Bold = True

    [!includeSupport and feedback]

    Понравилась статья? Поделить с друзьями:
  • Vba excel выделить текст в textbox
  • Vba excel выделить строку в диапазоне
  • Vba excel выделить строку в listbox
  • Vba excel выделить строку rows
  • Vba excel выделить столбец ячеек