Vba excel изменение цвета шрифта

Изменение цвета текста (шрифта) в ячейке рабочего листа Excel с помощью кода VBA. Свойства ячейки (диапазона) .Font.Color, .Font.ColorIndex и .Font.TintAndShade.

Использование цветовой палитры для присвоения цвета тексту в ячейке листа Excel аналогично присвоению цвета фону ячейки, только свойство диапазона .Interior меняем на свойство .Font.

Цвет текста и предопределенные константы

Цвет шрифту в ячейке можно присвоить с помощью предопределенных констант:

Range(«A1:C3»).Font.Color = vbGreen

Range(Cells(4, 1), Cells(6, 3)).Font.Color = vbBlue

Cells(7, 1).Font.Color = vbRed

Напомню, что вместо индексов строк и столбцов можно использовать переменные. Список предопределенных констант смотрите здесь.

Цвет шрифта и модель RGB

Для изменения цвета текста в ячейке можно использовать цветовую модель RGB:

Range(«A1»).Font.Color = RGB(200, 150, 250)

Cells(2, 1).Font.Color = RGB(200, 150, 100)

Аргументы функции RGB могут принимать значения от 0 до 255. Если все аргументы равны 0, цвет — черный, если все аргументы равны 255, цвет — белый. Функция RGB преобразует числовые значения основных цветов (красного, зеленого и синего) в индекс основной палитры.

Список стандартных цветов с RGB-кодами смотрите в статье: HTML. Коды и названия цветов.

Свойство .Font.ColorIndex

Свойство .Font.ColorIndex может принимать значения от 1 до 56. Это стандартная ограниченная палитра, которая существовала до Excel 2007 и используется до сих пор. Посмотрите примеры:

Range(«A1:D6»).Font.ColorIndex = 5

Cells(1, 6).Font.ColorIndex = 12

Таблица соответствия значений ограниченной палитры цвету:

Стандартная палитра Excel из 56 цветов

Стандартная палитра Excel из 56 цветов

Подробнее о стандартной палитре Excel смотрите в статье: Стандартная палитра из 56 цветов.

Свойство .Font.ThemeColor

Свойство .Font.ThemeColor может принимать числовые или текстовые значения констант из коллекции MsoThemeColorIndex:

Range(«A1»).Font.ThemeColor = msoThemeColorHyperlink

Cells(2, 1).Font.ThemeColor = msoThemeColorAccent4

Основная палитра

Основная палитра, начиная c Excel 2007, состоит из 16777216 цветов. Свойство .Font.Color может принимать значения от 0 до 16777215, причем 0 соответствует черному цвету, а 16777215 — белому.

Cells(1, 1).Font.Color = 0

Cells(2, 1).Font.Color = 6777215

Cells(3, 1).Font.Color = 4569325

Отрицательные значения свойства .Font.Color

При записи в Excel макрорекордером макроса с присвоением шрифту цвета используются отрицательные значения свойства .Font.Color, которые могут быть в пределах от -16777215 до -1. Отрицательные значения соответствуют по цвету положительному значению, равному сумме наибольшего индекса основной палитры и данного отрицательного значения. Например, отрицательное значение -8257985 соответствует положительному значению 8519230, являющегося результатом выражения 16777215 + (-8257985). Цвета текста двух ячеек из следующего кода будут одинаковы:

Cells(1, 1).Font.Color = 8257985

Cells(2, 1).Font.Color = 8519230

Свойство .Font.TintAndShade

Еще при записи макроса с присвоением шрифту цвета макрорекордером добавляется свойство .Font.TintAndShade, которое осветляет или затемняет цвет и принимает следующие значения:

  • -1 — затемненный;
  • 0 — нейтральный;
  • 1 — осветленный.

При тестировании этого свойства в Excel 2016, сравнивая затемненные и осветленные цвета, разницы не заметил. Сравните сами:

Sub Test()

With Range(Cells(1, 1), Cells(3, 1))

   .Value = «Сравниваем оттенки»

   .Font.Color = 37985

End With

Cells(1, 1).Font.TintAndShade = 1

Cells(2, 1).Font.TintAndShade = 0

Cells(3, 1).Font.TintAndShade = 1

End Sub

В первые три ячейки первого столбца записывается одинаковый текст для удобства сравнения оттенков.

Разноцветный текст в ячейке

Отдельным частям текста в ячейке можно присвоить разные цвета. Для этого используется свойство Range.Characters:

Sub Test()

    With Range(«A1»)

        .Font.Color = vbBlack

        .Value = «Океан — Солнце — Оазис»

        .Font.Size = 30

        .Characters(1, 5).Font.Color = vbBlue

        .Characters(9, 6).Font.Color = RGB(255, 230, 0)

        .Characters(18, 5).Font.Color = RGB(119, 221, 119)

    End With

End Sub

Результат работы кода:

Разноцветный текст в ячейке


Return to VBA Code Examples

In this Article

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

VBA Cell Font

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

Range("A1).Font.

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

Цвет шрифта Excel VBA

Свойство VBA Font Color можно использовать для изменения цвета шрифта ячеек Excel с помощью кода VBA. Используя индекс цвета и свойство цвета с функцией RGB, мы можем изменить цвет шрифта несколькими способами.

Когда мы готовим информационную панель в excelПодготовка информационной панели в ExcelИнформационная панель в Excel — это расширенный инструмент визуализации, который предоставляет обзор важнейших показателей и точек данных для бизнеса. Преобразовывая необработанные данные в содержательную информацию, информационная панель упрощает процесс принятия решений и анализа данных. Подробнее, мы обычно тратим много времени на форматирование ячеек, шрифты и т. д. Часто мы чувствуем себя косметологами Excel, глядя на различные цвета. форматирования Excel. Например, изменение цвета шрифта на листе Excel — простая задача, но когда дело доходит до Excel, вы должны знать, как писать код VBA. Написание кода VBA Код VBA — это набор инструкций, написанных пользователем в программировании приложений Visual Basic. языка в редакторе Visual Basic (VBE) для выполнения определенной задачи. Подробнее об изменении цвета шрифта.

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

Диапазон («A1:A10»)

Затем нам нужно выбрать свойство FONT.

Диапазон («A1:A10»). Шрифт

Тогда что мы хотим сделать с этим шрифтом? Итак, выберите цвет.

Диапазон («A1:A10»). Шрифт. Цвет

Таким образом, нам нужно создать код для изменения цвета шрифта. Это не выглядит легко.

Но помните, вначале все кажется трудным. Позже вы освоитесь.

Оглавление

  • Цвет шрифта Excel VBA
    • Как изменить цвет шрифта с помощью VBA?
      • Пример №1 – Использование цветового индекса
      • Пример №2 – Использование свойства цвета
      • Пример №3 – Использование свойства цвета с функцией RGB
    • Рекомендуемые статьи

Цвет шрифта VBA

Как изменить цвет шрифта с помощью VBA?

.free_excel_div{фон:#d9d9d9;размер шрифта:16px;радиус границы:7px;позиция:относительная;margin:30px;padding:25px 25px 25px 45px}.free_excel_div:before{content:»»;фон:url(центр центр без повтора #207245;ширина:70px;высота:70px;позиция:абсолютная;верх:50%;margin-top:-35px;слева:-35px;граница:5px сплошная #fff;граница-радиус:50%} Вы можете скачать этот шаблон Excel цвета шрифта VBA здесь — Цвет шрифта VBA Шаблон Excel

Пример №1 – Использование цветового индекса

Свойство Color Index отличается от свойства Color в VBAColor Свойство В VBAVBA Color Index используется для изменения цветов ячеек или диапазонов ячеек. Эта функция имеет уникальную идентификацию для различных типов цветов.Подробнее. Используя числовые значения, мы можем изменить цвет ячеек и шрифтов.

Числа варьируются от 1 до 56, и каждое число представляет разные цвета. Ниже приведен список чисел и их цветов.

Пример цвета шрифта VBA 1

Давайте проверим это.

У нас есть значение в ячейке A1.

Пример цвета шрифта VBA 1-1

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

Код:

Sub FontColor_Example1() Range («A1»). Font.ColorIndex = 10 End Sub

Это изменит цвет шрифта ячейки A1 на зеленый.

Пример VBA FontColor 1-2

Мы также можем использовать свойство CELLS для изменения цвета шрифта.

Код:

Sub FontColor_Example1() Cells(1, 1).Font.ColorIndex = 10 End Sub

Таким образом, мы можем использовать числа от 1 до 56, чтобы применить желаемый цвет к шрифту.

Пример №2 – Использование свойства цвета

Color Index имеет очень ограниченное количество цветов от 1 до 56, но с помощью свойства COLOR мы можем использовать 8 встроенных цветов: vbBlack, vbRed, vbGreen, vbBlue, vbYellow, vbMagenta, vbCyan, vbWhite.

Для этих цветов нам не нужно указывать какие-либо числа. Скорее, мы можем получить к ним доступ, используя их имя, как показано выше. Ниже приведен пример кода для всех 8 цветов.

Код:

Sub vbBlack_Example() Range(«A1»).Font.Color = vbBlack End Sub

Код:

Sub vbRed_Example() Range(«A1»).Font.Color = vbRed End Sub

Код:

Sub vbGreen_Example() Range(«A1»).Font.Color = vbGreen End Sub

Код:

Sub vbBlue_Example() Range(«A1»).Font.Color = vbBlue End Sub

Код:

Sub vbYellow_Example() Range(«A1»).Font.Color = vbYellow End Sub

Код:

Sub vbMagenta_Example() Range(«A1»).Font.Color = vbMagenta End Sub

Код:

Sub vbCyan_Example() Range(«A1»).Font.Color = vbCyan End Sub

Код:

Sub vbWhite_Example() Range(«A1»).Font.Color = vbWhite End Подпример №3 — Использование свойства цвета с функцией RGB

Мы видели, что у нас есть только 8 встроенных цветов для работы. Но нам нужно использовать функцию RGB, чтобы иметь разные цвета. Помимо встроенных цветов, мы можем создавать наши цвета с помощью VBA VBA RGBVBA RGBRGB также можно назвать красным, зеленым и синим, эта функция используется для получения числового значения значения цвета, эта функция имеет три компонента: диапазон, и они красный, синий и зеленый, другие цвета рассматриваются как компоненты этих трех разных цветов в функции VBA.

Посмотрите на синтаксис функции RGB.

RGB (красный, зеленый, синий)

RGB означает «красный, зеленый и синий». Поэтому нам нужно предоставить числа от 0 до 255 для каждого цвета, чтобы построить цвета.

Ниже приведены несколько примеров для вас.

Пример VBA FontColor 3

Ниже приведены некоторые примеры кода макроса.

Код:

Sub RGB_Example() Range(«A1»).Font.Color = RGB(0, 0, 0) ‘Изменить цвет шрифта на черный End Sub

Код:

Sub RGB_Example() Range(«A1»).Font.Color = RGB(16, 185, 199) ‘Цвет шрифта будет этим End Sub

Код:

Sub RGB_Example() Range(«A1»).Font.Color = RGB(106, 15, 19) ‘Цвет шрифта будет этим End Sub

Код:

Sub RGB_Example() Range(«A1»).Font.Color = RGB(216, 55, 19) ‘Цвет шрифта будет этим End Sub

Рекомендуемые статьи

Эта статья была руководством по цвету шрифта VBA. Здесь мы узнаем, как изменить цвет шрифта, используя индекс цвета VBA, свойство цвета с функцией RGB вместе с примерами и загрузим шаблон Excel. Ниже приведены некоторые полезные статьи Excel, связанные с VBA:

  • Примеры VBA
  • ЧДир ВБА
  • Альтернативный цвет строки в Excel

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

    A quick tip: the Excel Palette has two rows of colours which are rarely used and can usually be set to custom values without visible changes to other peoples’ sheets.

    Here’s the code to create a reasonable set of ‘soft-tone’ colours which are far less offensive than the defaults:

    
    

    Public Sub SetPalePalette(Optional wbk As Excel.Workbook) ' This subroutine creates a custom palette of pale tones which you can use for controls, headings and dialogues '

    ' ** THIS CODE IS IN THE PUBLIC DOMAIN ** ' Nigel Heffernan http://Excellerando.Blogspot.com

    ' The Excel color palette has two hidden rows which are rarely used: ' Row 1: colors 17 to 24 ' Row 2: colors 25 to 32 - USED BY SetGrayPalette in this workbook '

    ' Code to capture existing Screen Updating settting and, if necessary, ' temporarily suspend updating while this procedure generates irritating ' flickers onscreen... and restore screen updating on exit if required.

    Dim bScreenUpdating As Boolean

    bScreenUpdating = Application.ScreenUpdating

    If bScreenUpdating = True Then Application.ScreenUpdating = False End If

    'If Application.ScreenUpdating <> bScreenUpdating Then ' Application.ScreenUpdating = bScreenUpdating 'End If

    If wbk Is Nothing Then Set wbk = ThisWorkbook End If

    With wbk

    .Colors(17) = &HFFFFD0  ' pale cyan
    .Colors(18) = &HD8FFD8  ' pale green.
    .Colors(19) = &HD0FFFF  ' pale yellow
    .Colors(20) = &HC8E8FF  ' pale orange
    .Colors(21) = &HDBDBFF  ' pale pink
    .Colors(22) = &HFFE0FF  ' pale magenta
    .Colors(23) = &HFFE8E8  ' lavender
    .Colors(24) = &HFFF0F0  ' paler lavender
    

    End With

    If Application.ScreenUpdating <> bScreenUpdating Then
    Application.ScreenUpdating = bScreenUpdating
    End If

    End Sub

    Public Sub SetGreyPalette()
    ' This subroutine creates a custom palette of greyshades which you can use for controls, headings and dialogues

    ' ** THIS CODE IS IN THE PUBLIC DOMAIN **
    ' Nigel Heffernan http://Excellerando.Blogspot.com

    ' The Excel color palette has two hidden rows which are rarely used:
    ' Row 1: colors 17 to 24 ' - USED BY SetPalePalette in this workbook
    ' Row 2: colors 25 to 32

    ' Code to capture existing Screen Updating settting and, if necessary,
    ' temporarily suspend updating while this procedure generates irritating
    ' flickers onscreen... remember to restore screen updating on exit!

    Dim bScreenUpdating As Boolean

    bScreenUpdating = Application.ScreenUpdating

    If bScreenUpdating = True Then
    Application.ScreenUpdating = False
    End If

    'If Application.ScreenUpdating <> bScreenUpdating Then
    ' Application.ScreenUpdating = bScreenUpdating
    'End If

    With ThisWorkbook
    .Colors(25) = &HF0F0F0
    .Colors(26) = &HE8E8E8
    .Colors(27) = &HE0E0E0
    .Colors(28) = &HD8D8D8
    .Colors(29) = &HD0D0D0
    .Colors(30) = &HC8C8C8
    ' &HC0C0C0 ' Skipped &HC0C0C0 - this is the regular 25% grey in the main palette
    .Colors(31) = &HB8B8B8 ' Note that the gaps are getting wider: the human eye is more sensitive
    .Colors(32) = &HA8A8A8 ' to changes in light greys, so this will be perceived as a linear scale
    End With

    'The right-hand column of the Excel default palette specifies the following greys:

    ' Colors(56) = &H333333
    ' Colors(16) = &H808080
    ' Colors(48) = &H969696
    ' Colors(15) = &HC0C0C0 ' the default '25% grey'

    ' This should be modified to improve the color 'gap' and make the colours easily-distinguishable:

    With ThisWorkbook
    .Colors(56) = &H505050
    .Colors(16) = &H707070
    .Colors(48) = &H989898
    ' .Colors(15) = &HC0C0C0
    End With

    If Application.ScreenUpdating <> bScreenUpdating Then
    Application.ScreenUpdating = bScreenUpdating
    End If

    End Sub

    You may choose to write a ‘CaptureColors’ and ‘ReinstateColors’ function for each workbook’s Open() and BeforeClose() events… Or even for each worksheet’s activate and deactivate event.

    I have code lying around somewhere that creates a ‘thermal’ colour gradient for 3-D charts, giving you a progression from ‘Cold’ blue to ‘Hot’ reds in thirty-two steps. This is harder than you might think: a gradient of colors that will be perceived as ‘equal intervals’ by the human visual system (which runs on a logarithmic scale of intensity and has nonlinear weightings for red, green and blue as ‘strong’ colours) takes time to construct — and you have to use VBA to coerce MS Chart into using the colours you specify, in the order you specified.

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