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

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

    Return to VBA Code Examples

    In this Article

    • VBA Cell Font
    • Change Font Color
      • vbColor
      • Color – RGB
      • ColorIndex
    • Font Size
    • Bold Font
    • Font Name
    • Cell Style

    VBA Cell Font

    In VBA, you can change font properties using the VBA Font Property of the Range Object. Type the following code into the VBA Editor and you’ll see a list of all the options available:

    Range("A1).Font.

    vba cell font

    We will discuss a few of the most common properties below.

    Change Font Color

    There are a few ways to set font colors.

    vbColor

    The easiest way to set colors is with vbColors:

    Range("a1").Font.Color = vbRed

    However, you’re very limited in terms of colors available. These are the only options available:

    vba vbcolor

    Color – RGB

    You can also set colors based on RGB (Red Green Blue). Here you enter color values between 0-255 for Red, Green, and Blue. Using those three colors you can make any color:

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

    ColorIndex

    VBA / Excel also has a ColorIndex property. This makes pre-built colors available to you. However, they’re stored as Index numbers, which makes it hard to know what color is what:

    Range("a1").Font.ColorIndex = …..

    We wrote an article about VBA Color codes, including a list of the VBA ColorIndex codes. There you can learn more about colors.

    Font Size

    This will set the font size to 12:

    Range("a1").Font.Size = 12

    or to 16:

    Range("a1").Font.Size = 16

    VBA Coding Made Easy

    Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

    automacro

    Learn More

    Bold Font

    It is easy to set a cell font to Bold:

    Range("A1").Font.Bold = True

    or to clear Bold formatting:

    Range("A1").Font.Bold = False

    Font Name

    To change a font name use the Name property:

    Range("A1").Font.Name = "Calibri"
    Range("A1").Font.Name = "Arial"
    Range("A1").Font.Name = "Times New Roman"

    Cell Style

    Excel offers the ability to create Cell “Styles”. Styles can be found in the Home Ribbon > Styles:

    excel vba font 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:

    cell formatting menu excel

    Personally, for many of the models that I work on, I usually create an “Input” cell style:

    Range("a1").Style = "Input"

    By using styles you can also easily identify cell types on your worksheet.  The example below will loop through all the cells in the worksheet and change any cell with Style = “Input” to “InputLocked”:

    Dim Cell as Range
    
    For Each Cell in ActiveSheet.Cells
      If Cell.Style = "Input" then
        Cell.Style = "InputLocked"
      End If
    Next Cell

    В VBA вы можете изменить свойства шрифта с помощью свойства шрифта VBA объекта Range. Введите следующий код в редактор VBA, и вы увидите список всех доступных вариантов:

    Ниже мы обсудим несколько наиболее распространенных свойств.

    Изменить цвет шрифта

    Есть несколько способов установить цвета шрифта.

    vbColor

    Самый простой способ установить цвета — использовать vbColors:

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

    Однако количество доступных цветов очень ограничено. Это единственные доступные варианты:

    Цвет — RGB

    Вы также можете установить цвета на основе RGB (красный, зеленый, синий). Здесь вы вводите значения цвета от 0 до 255 для красного, зеленого и синего. Используя эти три цвета, вы можете сделать любой цвет:

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

    ColorIndex

    VBA / Excel также имеет свойство ColorIndex. Это делает вам доступными предварительно созданные цвета. Однако они хранятся в виде порядковых номеров, что затрудняет определение того, что это за цвет:

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

    Мы написали статью о цветовых кодах VBA, включая список кодов VBA ColorIndex. Там вы можете узнать больше о цветах.

    Размер шрифта

    Это установит размер шрифта на 12:

    1 Диапазон («a1»). Размер шрифта = 12

    или до 16:

    1 Диапазон («a1»). Размер шрифта = 16

    Жирный шрифт

    Установить полужирный шрифт ячейки легко:

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

    или очистить форматирование полужирным шрифтом:

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

    Название шрифта

    Чтобы изменить название шрифта, используйте Имя имущество:

    1 Диапазон («A1»). Font.Name = «Calibri»
    1 Диапазон («A1»). Font.Name = «Arial»
    1 Диапазон («A1»). Font.Name = «Times New Roman»

    Стиль ячейки

    Excel предлагает возможность создавать «стили» ячеек. Стили можно найти в Главная Лента> Стили:

    Стили позволяют сохранить желаемое форматирование ячеек. Затем назначьте этот стиль новой ячейке, и все форматирование ячейки будет немедленно применено. В том числе размер шрифта, цвет ячеек, состояние защиты ячеек и все остальное, что доступно в меню форматирования ячеек:

    Лично для многих моделей, над которыми я работаю, я обычно создаю стиль ячейки «Вход»:

    1 Диапазон («a1»). Style = «Input»

    Используя стили, вы также можете легко определять типы ячеек на вашем листе. В приведенном ниже примере выполняется цикл по всем ячейкам на листе и изменяется любая ячейка со Style = «Input» на «InputLocked»:

    1234567 Тусклая ячейка как диапазонДля каждой ячейки в ActiveSheet.CellsЕсли Cell.Style = «Input», тогдаCell.Style = «InputLocked»Конец, еслиСледующая ячейка

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

    Excel VBA Tutorial about setting font characteristics with macrosIn 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:

    1. Identify the cell range whose font you modify (Range).
    2. Refer to the Font object representing Range’s font (Font).
    3. 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.

    Macro example sets font to 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:

    1. Identify the cell range whose font you name you change (Range).
    2. Refer to the Font object representing Range’s font (Font).
    3. 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.

    Macro sets font face

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

    1. Identify the cell range whose font size you change (Range).
    2. Refer to the Font object representing Range’s font (Font).
    3. 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.

    Macro sets font size

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

    1. Identify the cell range whose font you style you change (Range).
    2. Refer to the Font object representing Range’s font (Font).
    3. 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.

    Macro sets font style

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

    1. Identify the cell range whose font you set to bold (Range).
    2. Refer to the Font object representing Range’s font (Font).
    3. 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.

    Macro sets font 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:

    1. Identify the cell range whose font you set to italic (Range).
    2. Refer to the Font object representing Range’s font (Font).
    3. 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.

    Macro sets font 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:

    1. Identify the cell range whose font you underline (Range).
    2. Refer to the Font object representing Range’s font (Font).
    3. 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.

    Macro sets font underline

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

    1. Identify the cell range whose font you strike through (Range).
    2. Refer to the Font object representing Range’s font (Font).
    3. 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.

    Macro font strikethrough

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

    1. Identify the cell range whose font color you change with the RGB color model (Range).
    2. Refer to the Font object representing Range’s font (Font).
    3. Specify the red, green and blue components of the color with the RGB function (RGB(Red, Green, Blue)).
    4. 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.

    Macro sets font color with RGB

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

    1. Identify the cell range whose font color you change with the ColorIndex property (Range).
    2. Refer to the Font object representing Range’s font (Font).
    3. 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.

    Macro sets font color with ColorIndex

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

    1. Identify the cell range whose font color you set to Automatic (Range).
    2. Refer to the Font object representing Range’s font (Font).
    3. 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).

    Macro sets font color to Automatic

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

    1. Identify the cell range whose font color you change with the theme color scheme (Range).
    2. Refer to the Font object representing Range’s font (Font).
    3. 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.

    Macro sets color with 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:

    1. Identify the cell range whose font tint and shade you change (Range).
    2. Refer to the Font object representing Range’s font (Font).
    3. 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.

    Macro sets font tint and shade

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

    1. Identify the cell range whose font you format as subscript (Range).
    2. Refer to the Font object representing Range’s font (Font).
    3. 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.

    Macro sets font 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:

    1. Identify the cell range whose font you format as superscript (Range).
    2. Refer to the Font object representing Range’s font (Font).
    3. 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.

    Macro sets font 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.

    Содержание

    1. Шрифт ячейки VBA — изменение цвета, размера, стиля и т. Д.
    2. Шрифт ячейки VBA
    3. Изменить цвет шрифта
    4. vbColor
    5. Цвет — RGB
    6. ColorIndex
    7. Размер шрифта
    8. Жирный шрифт
    9. Название шрифта
    10. Стиль ячейки
    11. VBA Cell Font – Change Color, Size, Style, & More
    12. VBA Cell Font
    13. Change Font Color
    14. vbColor
    15. Color – RGB
    16. ColorIndex
    17. Font Size
    18. VBA Coding Made Easy
    19. Bold Font
    20. Font Name
    21. Cell Style
    22. VBA Code Examples Add-in
    23. Свойство Worksheet.Cells (Excel)
    24. Синтаксис
    25. Замечания
    26. Пример
    27. Поддержка и обратная связь
    28. VBA Excel. Форматирование текста в ячейке (объект Font)
    29. Формат отображаемого значения
    30. Основные свойства объекта Font
    31. Примеры форматирования текста
    32. 5 комментариев для “VBA Excel. Форматирование текста в ячейке (объект Font)”

    Шрифт ячейки VBA — изменение цвета, размера, стиля и т. Д.

    Шрифт ячейки VBA

    В VBA вы можете изменить свойства шрифта с помощью свойства шрифта VBA объекта Range. Введите следующий код в редактор VBA, и вы увидите список всех доступных вариантов:

    Ниже мы обсудим несколько наиболее распространенных свойств.

    Изменить цвет шрифта

    Есть несколько способов установить цвета шрифта.

    vbColor

    Самый простой способ установить цвета — использовать vbColors:

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

    Однако количество доступных цветов очень ограничено. Это единственные доступные варианты:

    Цвет — RGB

    Вы также можете установить цвета на основе RGB (красный, зеленый, синий). Здесь вы вводите значения цвета от 0 до 255 для красного, зеленого и синего. Используя эти три цвета, вы можете сделать любой цвет:

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

    ColorIndex

    VBA / Excel также имеет свойство ColorIndex. Это делает вам доступными предварительно созданные цвета. Однако они хранятся в виде порядковых номеров, что затрудняет определение того, что это за цвет:

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

    Мы написали статью о цветовых кодах VBA, включая список кодов VBA ColorIndex. Там вы можете узнать больше о цветах.

    Размер шрифта

    Это установит размер шрифта на 12:

    1 Диапазон («a1»). Размер шрифта = 12
    1 Диапазон («a1»). Размер шрифта = 16

    Жирный шрифт

    Установить полужирный шрифт ячейки легко:

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

    или очистить форматирование полужирным шрифтом:

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

    Название шрифта

    Чтобы изменить название шрифта, используйте Имя имущество:

    1 Диапазон («A1»). Font.Name = «Calibri»
    1 Диапазон («A1»). Font.Name = «Arial»
    1 Диапазон («A1»). Font.Name = «Times New Roman»

    Стиль ячейки

    Excel предлагает возможность создавать «стили» ячеек. Стили можно найти в Главная Лента> Стили:

    Стили позволяют сохранить желаемое форматирование ячеек. Затем назначьте этот стиль новой ячейке, и все форматирование ячейки будет немедленно применено. В том числе размер шрифта, цвет ячеек, состояние защиты ячеек и все остальное, что доступно в меню форматирования ячеек:

    Лично для многих моделей, над которыми я работаю, я обычно создаю стиль ячейки «Вход»:

    1 Диапазон («a1»). Style = «Input»

    Используя стили, вы также можете легко определять типы ячеек на вашем листе. В приведенном ниже примере выполняется цикл по всем ячейкам на листе и изменяется любая ячейка со Style = «Input» на «InputLocked»:

    Источник

    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.

    Источник

    Свойство Worksheet.Cells (Excel)

    Возвращает объект Range , представляющий все ячейки на листе (а не только используемые в данный момент ячейки).

    Синтаксис

    выражение.Cells

    Выражение Переменная, представляющая объект Worksheet .

    Замечания

    Так как элемент по умолчанию объекта Range направляет вызовы с параметрами в свойство Item, можно указать индекс строки и столбца сразу после ключевого слова Cells, вместо явного вызова свойства Item.

    При использовании этого свойства без квалификатора объекта возвращается объект Range, который представляет все ячейки на активном листе.

    Пример

    В этом примере размер шрифта ячейки C5 на листе 1 активной книги устанавливается в 14 пунктов.

    В этом примере формула очищается в ячейке 1 на листе 1 активной книги.

    В этом примере шрифт и размер шрифта для каждой ячейки на листе Sheet1 устанавливается значение Arial из 8 точек.

    В этом примере выполняется переключение сортировки между порядком по возрастанию и убыванию при двойном щелчке любой ячейки в диапазоне данных. Данные сортируются по столбцу ячейки, дважды щелкнув которую.

    В этом примере выполняется просмотр столбца C активного листа, и для каждой ячейки с комментарием текст примечания помещается в столбец D и удаляется комментарий из столбца C.

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

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

    Источник

    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.

    VBA-макрос: заливка, шрифт, линии границ, ширина столбцов и высота строк

    В процессе запыления данных сотрудниками отдела на некоторых листах были изменены форматы ячеек:

    запыления планов работ.

    Необходимо сбросить форматирование ячеек и сделать так чтобы на всех таблицах планов выполнения работ были одинаковые форматы отображения данных. Формат ячеек для исходной таблицы должен быть закреплен за шаблоном, чтобы можно было сделать сброс и применять заданный стиль оформления в дальнейшем.

    Чтобы выполнять такие задачи вручную можно попытаться облегчить процесс настройки множества опций форматирования для многих диапазонов ячеек на разных листах и рабочих книгах. Плюс к о всему можно ошибиться и применить несколько другие настройки форматирования.

    Макросы Excel прекрасно справляются с форматированием ячеек на рабочих листах. Кроме того, делают это быстро и в полностью автоматическом режиме. Воспользуемся этими преимуществами и для решения данной задачи напишем свой код VBA-макроса. Он поможет нам быстро и безопасно сбрасывать форматы на исходный предварительно заданный в шаблоне главной таблицы.

    Чтобы написать свой код макроса откройте специальный VBA-редактор в Excel: «РАЗРАБОТЧИК»-«Код»-«Visual Basic» или нажмите комбинацию клавиш ALT+F11:

    Код Visual Basic.

    В редакторе создайте новый модуль выбрав инструмент «Insert»-«Module» и введите в него такой VBA-код макроса:

    Sub SbrosFormat()
    If TypeName(Selection) <> "Range" Then Exit Sub
    With Selection
    .HorizontalAlignment = xlVAlignCenter
    .VerticalAlignment = xlVAlignCenter
    .WrapText = True
    .Borders.LineStyle = xlContinuous
    .Borders.Weight = xlThin
    .Font.ColorIndex = xlColorIndexAutomatic
    .Interior.ColorIndex = xlColorIndexAutomatic
    .Columns.AutoFit
    .Rows.AutoFit
    End With
    End Sub

    VBA-код макроса.

    Теперь если нам нужно сбросить форматирование таблицы на исходный формат отображения ее данных, выделите диапазон ячеек A1:E20 и запустите макрос: «РАЗРАБОЧТИК»-«Код»-«Макросы»-«SbrosFormat»-«Выполнить». Результат работы макроса изображен ниже на рисунке:

    сбросить форматирование таблицы на исходный формат.

    Таблица приобрела формат, который определен макросом. Таким образом код VBA нам позволяет сбросить любые изменения формата ячеек на предустановленный автором отчета.

    

    Описание VBA-макроса для формата ячеек таблицы Excel

    Первая инструкция в коде, проверяет выделены ли ячейки диапазоном. Если перед выполнением макроса выделил другой элемент листа, например, график, тогда макрос закрывается и дальнейшие инструкции выполняться не будут. В противные случаи будут форматироваться все выделенные ячейки по очереди в соответствии с определенными настройками форматирования:

    1. Текст в значениях ячеек выравнивается по центру горизонтально и вертикально.
    2. Включен построчный перенос текста.
    3. Все границы ячеек получают черную обычной толщины непрерывную линию с черным цветом.
    4. Сброс цвета шрифта на авто.
    5. Удаляется любая заливка ячеек.
    6. Ширина столбцов автоматически настраивается под текст в ячейках.
    7. Автоматически настроить высоту строк по содержимому ячеек.

    Модификация исходного кода макроса для форматирования

    Если необходимо сделать так чтобы текст выравнивался не по центру относительно горизонтали, а по правую сторону ячейки, тогда измените константу xlHAlignCenter на xlHAlignRight. Она находиться в свойстве .HorizontalAlignment. Сделайте это следующим образом:

    .HorizontalAlignment = xlHAlignRight.

    Таким же образом можно выровнять текст по левую сторону изменив значение константы на xlHAlignLeft. Или можно выровнять положение текста по ширине ячейки используя константу xlHAlignJustify.

    Чтобы макрос выравнивал текст в ячейках по вертикали к низу, измените строку кода, отвечающую за данную настройку форматирования. Измените константу, которая присваивается к свойству VerticalAlignment в следующий способ:

    Если хотите выровнять текс к верху ячейки, тогда воспользуйтесь константой xlHAlignTop.

    Если нужно применить для границ ячеек толстую и пунктирную линию в синем цвете, смодифицируйте инструкцию, отвечающую за формат линий:

    .Borders.LineStyle = xlDash

    .Borders.Color = vbBlue

    .Borders.Weight = xlMedium

    Описание настройки форматирования для линий границ ячеек. Мы будем получать разные дополнительные типы линий границ если для свойства LineStyle присваивать такие константы:

    • xlDoshDot – применяется для рисования пунктирных линий в границах ячеек;
    • xlDouble – рисует двойную линию;
    • xlHairLine – рисует тонкую линию;
    • xlThick – для рисования очень толстой линии.

    Для настройки цвета линий Excel предлагает всего 8 констант для определенных цветов. Константы для настройки цвета линий границ для свойства Color:

    • vbBlack – черный;
    • vbWhite – белый;
    • vbRed – красный;
    • vbGreen –зеленый;
    • vbBlue – синий;
    • vbYellow – желтый;
    • vbMagenta – алый;
    • vbCyan – голубой.

    Но при необходимости присвоить линиям границ другие цвета можно вместо константы для свойства Color записать функцию RGB(). Достаточно лишь в аргументе этой функции указать код цвета по шкале от 0 и до 255.

    Если нужно применить толстую линию только для границ выделенного диапазона, тогда перед инструкцией End With добавьте следующую строку кода:

    .BorderAround xlContinuous, xlMedium, vbBlack

    Описание: В первом аргументе для метода BorderAround можно записать также другой стиль линии. Во втором – толщину линии, а в третьем – цвет. Константы, которые можно присвоить в качестве значений для этих аргументов можно использовать те же, которые мы использовали для свойств: LineStyle, Weight, Color.

    Если нужно экспонировать первую строку для выделенного диапазона с помощью жирного и курсивного шрифта значений ячеек. А также заполнить ячейки первой строки заливкой с голубым цветом, тогда в самом конце кода макроса перед последней инструкцией End Sub следует добавить несколько строк с VBA-кодом:

    .Rows(1).Font.Bold = True

    .Rows(1).Font.Italic = True

    .Rows(1).Interior.Color = vbCyan

    Если хотите присвоить такой же формат для не только для первой строки, но и для первого столбца выделенного диапазона, тогда скопируйте и вставьте ниже эти 3 строчки кода. После в последних трех строках измените свойство Rows на Columns.

    .Columns (1).Font.Bold = True

    .Columns (1).Font.Italic = True

    .Columns (1).Interior.Color = vbCyan

    Если нужно задать особенный формат для экспонирования последней строки выделенного диапазона, тогда измените число 1 в аргументе свойства Rows на число всех выделенных строк .Rows.Count. Например, добавьте в конец кода еще такую строку:

    .Rows(.Rows.Count).Font.Bold = True

    Полная версия модифицированного кода макроса выглядит так:

    Sub SbrosFormat()
    If TypeName(Selection) <> "Range" Then Exit Sub
    With Selection
    .HorizontalAlignment = xlVAlignCenter
    .VerticalAlignment = xlVAlignCenter
    .WrapText = True
    .Borders.LineStyle = xlDash
    .Borders.Color = vbBlue
    .Borders.Weight = xlMedium
    .Font.ColorIndex = xlColorIndexAutomatic
    .Interior.ColorIndex = xlColorIndexAutomatic
    .Columns.AutoFit
    .Rows.AutoFit
    .BorderAround xlContinuous, xlMedium, vbBlack
    .Rows(1).Font.Bold = True
    .Rows(1).Font.Italic = True
    .Rows(1).Interior.Color = vbCyan
    .Columns(1).Font.Bold = True
    .Columns(1).Font.Italic = True
    .Columns(1).Interior.Color = vbCyan
    .Rows(.Rows.Count).Font.Bold = True
    End With
    End Sub

    Пример работы измененного кода VBA-макроса:

    Пример после изменений в коде.

    В данном примере вы ознакомились с базовыми возможностями форматирования с помощью VBA-макросов. Уверен, что теперь вы сможете самостоятельно найти практическое применение этим исходным кодам.

     

    Oleksandr

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

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

    Есть много ячеек, в каждой ячейке текст (две строчки), например

    Текст 1
    Текст 2

    параметры шрифта для обоих текстов (Calibri, размер 11)

    нужно написать макрос который будет менять параметры шрифта в выбранных ячейках
    нужно Текст 1 уменьшить размер с 11 уменьшить до 9
    а Текст 2 увеличить размер с 11 до 13 и сделать текст полужирным.
    Текст 1
    Текст 2

    Хотелось бы чтобы макрос работал для всех выделенных ячеек…
    Спасибо…[ :)

    Изменено: Oleksandr07.09.2017 10:46:53

     

    V

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

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

    файл покажите. или какой разделитель между текст1 и текст2. символ10 или просто через формат ячейки «перенос по словам»?

     

    Oleksandr

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

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

    разделитель между текстами СИМВОЛ (10)…
    в шапку добавить пример файла…

     

    V

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

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

    а теперь согласно файла в каком столбце это все должно происходить.

     

    Oleksandr

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

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

    исходные данные в столбце E… можно редактировать прямо там (но там внутри формула)…
    или скопировать в соседний столбец F (отредактированный текст из E)…
    как проще так и сделайте…

    Спасибо :)

    Изменено: Oleksandr07.09.2017 17:27:44

     

    Alemox

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

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

    #6

    07.09.2017 10:59:11

    Код
    Sub Alemox()
    Dim a As Integer
    Dim Ячейка As Range
    For Each Ячейка In Selection.Cells
        For a = 1 To Len(Ячейка.Text) Step 1
            If Mid(Ячейка.Text, a, 1) = Chr(10) Then
                Ячейка.Characters(Start:=1, Length:=a).Font.Size = 10
                With Ячейка.Characters(Start:=a + 1, Length:=Len(Ячейка.Text) - a).Font
                    .Size = 14
                    .Bold = True
                End With
                Exit For
            End If
        Next a
    Next Ячейка
    End Sub

    Но данное изменение не применимо для формул

    Мастерство программиста не в том, чтобы писать программы, работающие без ошибок.
    А в том, чтобы писать программы, работающие при любом количестве ошибок.

     

    Alemox

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

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

    файл с примером

    Мастерство программиста не в том, чтобы писать программы, работающие без ошибок.
    А в том, чтобы писать программы, работающие при любом количестве ошибок.

     

    Oleksandr

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

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

    #8

    07.09.2017 11:08:25

    Цитата
    Alemox написал:
    Но данное изменение не применимо для формул

    тогда я скопирую (как значения)  данные из ячеек с формулами в соседний столбец и к нему применю Ваш макрос…

    Спасибо!!!  :)
    Макрос работает так как и хотелось…. :D

     

    V

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

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

    #9

    07.09.2017 11:25:49

    еще вариант (копирует выделенное в соседний столбец справа и там обрабатывает)

    Код
    Sub vvv()
    Application.ScreenUpdating = False
    Selection.Copy
    Selection.Offset(, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
            :=False, Transpose:=False
    Application.CutCopyMode = False
    For Each t In Selection
    n = InStr(t, Chr(10))
       With t.Characters(Start:=1, Length:=n).Font
            .FontStyle = "обычный"
            .Size = 9
       End With
       With t.Characters(Start:=n + 1, Length:=99).Font
            .FontStyle = "полужирный"
            .Size = 13
       End With
    Next
    Application.ScreenUpdating = True
    End Sub

    Изменено: V07.09.2017 11:28:11

     

    Oleksandr

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

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

    #10

    07.09.2017 11:29:45

    Цитата
    V написал:
    еще вариант

    о этот макрос сам и копирует отредактированные данные в соседний столбец…
    Спасибо!!! :D  

     

    kuklp

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

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

    E-mail и реквизиты в профиле.

    #11

    07.09.2017 11:42:56

    На месте, без вн. цикла:

    Код
    Sub www()
        Dim c As Range, a
        With Selection
            a = .Value: .NumberFormat = "@": .Value = a
            .Font.Size = 10:
            For Each c In .Cells
                c.Characters(InStr(1, c, Chr(10)) + 1).Font.Size = 14
                c.Characters(InStr(1, c, Chr(10)) + 1).Font.Bold = True
            Next
        End With
    End Sub

    Я сам — дурнее всякого примера! …

    Понравилась статья? Поделить с друзьями:
  • Vba excel как изменить цвет текста
  • Vba excel как изменить формат ячейки
  • Vba excel как защитить макросы
  • Vba excel как защитить макрос
  • Vba excel как запустить форму