Format color vba excel

Содержание

  1. Объект ColorFormat (Excel)
  2. Замечания
  3. Пример
  4. Свойства
  5. См. также
  6. Поддержка и обратная связь
  7. Excel VBA: ColorIndex Codes List & RGB Colors
  8. VBA Color Index Codes List
  9. VBA ColorIndex Examples
  10. Set Cell Background Color
  11. Set Cell Font Color
  12. Set Cell Borders Color
  13. Get Cell Background ColorIndex
  14. Set a Cell Background Color to Another Cell’s Color
  15. VBA Color Property
  16. VB Color
  17. Set Cell Background Color
  18. Set Cell Font Color
  19. Set Cell Borders Color
  20. Set a Cell Background Color to Another Cell’s Color
  21. RGB Colors
  22. ColorIndex Codes List & RGB Colors in Access VBA
  23. VBA Code Examples Add-in
  24. Formatting a Range of Cells In Excel VBA
  25. Formatting Cells Number
  26. General
  27. Number
  28. Currency
  29. Accounting
  30. Percentage
  31. Fraction
  32. Scientific
  33. Special
  34. Custom
  35. Formatting Cells Alignment
  36. Text Alignment
  37. Horizontal
  38. Vertical
  39. Text Control
  40. Wrap Text
  41. Shrink To Fit
  42. Merge Cells
  43. Right-to-left
  44. Text direction
  45. Orientation
  46. Font Name
  47. Font Style
  48. Font Size
  49. Underline
  50. Font Color
  51. Font Effects
  52. Strikethrough
  53. Subscript
  54. Superscript
  55. Border
  56. Border Index
  57. Line Style
  58. Line Thickness
  59. Line Color
  60. Pattern Style
  61. Protection
  62. Locking Cells
  63. Hiding Formulas

Объект ColorFormat (Excel)

Представляет цвет одноцветного объекта, цвет переднего плана или фона объекта с градиентной или узорчатой заливкой или цвет указателя.

Замечания

Для цветов можно задать явное красно-зелено-синее значение (с помощью свойства RGB ) или цвет в цветовой схеме (с помощью свойства SchemeColor ).

Используйте одно из свойств, перечисленных в следующей таблице, чтобы вернуть объект ColorFormat .

Использование этого свойства С этим объектом Возврат объекта ColorFormat, представляющего этот цвет
BackColor FillFormat Цвет заливки фона (используется в заливке с затенением или узором)
ForeColor FillFormat Цвет заливки переднего плана (или просто цвет заливки для сплошной заливки)
BackColor LineFormat Цвет линии фона (используется в узорчатой линии)
ForeColor LineFormat Цвет линии переднего плана (или просто цвет линии для сплошной линии)
ForeColor ShadowFormat Цвет тени
ExtrusionColor ThreeDFormat Цвет сторон экструдированного объекта

Пример

Используйте свойство RGB , чтобы задать для цвета явное красно-зелено-синее значение. В следующем примере в myDocument добавляется прямоугольник, а затем задается цвет переднего плана, цвет фона и градиент для заливки прямоугольника.

Свойства

См. также

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

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

Источник

Excel VBA: ColorIndex Codes List & RGB Colors

In this Article

VBA Color Index Codes List

When using VBA to code the Colorindex (or background color) of a cell it is useful to know what integer will equal what color. Below is a reference picture which shows the color and lists it’s respective Colorindex. aka VBA Color Palette

Here’s the code to make one for yourself, or just bookmark this page:

VBA ColorIndex Examples

Set Cell Background Color

This example sets the cell’s background color.

Set Cell Font Color

This example sets the cell’s font color.

Set Cell Borders Color

This example sets the cell’s border color.

Get Cell Background ColorIndex

This example gets the cell’s background color and assigns it to an Integer variable.

Set a Cell Background Color to Another Cell’s Color

This example sets a cell color equal to another cell color.

VBA Color Property

Instead of using Excel / VBA’s ColorIndex property, you can use the Color property. The Color property takes two input types:

We will discuss these below:

VB Color

VB Color is the easiest way to set colors in VBA. However, it’s also the least flexible. To set a color code using vbColor use the table below:

However, as you can see from the table, your options are extremely limited.

Set Cell Background Color

Set Cell Font Color

Set Cell Borders Color

Set a Cell Background Color to Another Cell’s Color

RGB Colors

RGB stands for Red Green Blue. These are the three primary colors that can be combined to produce any other color. When entering colors as RGB, enter a value between 0 and 255 for each color code.

Here’s an example:

Above we’ve set Red = 255 (max value), Green = 255 (max value), and Blue = 0 (min value). This sets the cell background color to Yellow.

Instead we can set the cell font color to purple:

There are numerous online tools to find the RGB code for your desired color (here’s one).

ColorIndex Codes List & RGB Colors in Access VBA

Access uses forms to display data. You can use the ColorIndex Codes to programmatically change the background color and foreground color of objects in your Access forms.

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.

Источник

Formatting a Range of Cells In Excel VBA

Formatting Cells Number

General

Number

Currency

Accounting

Percentage

Fraction

Scientific

Special

Custom

Formatting Cells Alignment

Text Alignment

Horizontal

The value of this property can be set to one of the constants: xlGeneral, xlCenter, xlDistributed, xlJustify, xlLeft, xlRight.

The following code sets the horizontal alignment of cell A1 to center.

Vertical

The value of this property can be set to one of the constants: xlBottom, xlCenter, xlDistributed, xlJustify, xlTop.

The following code sets the vertical alignment of cell A1 to bottom.

Text Control

Wrap Text

This example formats cell A1 so that the text wraps within the cell.

Shrink To Fit

This example causes text in row one to automatically shrink to fit in the available column width.

Merge Cells

This example merge range A1:A4 to a large one.

Right-to-left

Text direction

The value of this property can be set to one of the constants: xlRTL (right-to-left), xlLTR (left-to-right), or xlContext (context).

The following code example sets the reading order of cell A1 to xlRTL (right-to-left).

Orientation

The value of this property can be set to an integer value from –90 to 90 degrees or to one of the following constants: xlDownward, xlHorizontal, xlUpward, xlVertical.

The following code example sets the orientation of cell A1 to xlHorizontal.

Font Name

The value of this property can be set to one of the fonts: Calibri, Times new Roman, Arial.

The following code sets the font name of range A1:A5 to Calibri.

Font Style

The value of this property can be set to one of the constants: Regular, Bold, Italic, Bold Italic.

The following code sets the font style of range A1:A5 to Italic.

Font Size

The value of this property can be set to an integer value from 1 to 409.

The following code sets the font size of cell A1 to 14.

Underline

The value of this property can be set to one of the constants: xlUnderlineStyleNone, xlUnderlineStyleSingle, xlUnderlineStyleDouble, xlUnderlineStyleSingleAccounting, xlUnderlineStyleDoubleAccounting.

The following code sets the font of cell A1 to xlUnderlineStyleDouble (double underline).

Font Color

The value of this property can be set to one of the standard colors: vbBlack, vbRed, vbGreen, vbYellow, vbBlue, vbMagenta, vbCyan, vbWhite or an integer value from 0 to 16,581,375.

To assist you with specifying the color of anything, the VBA is equipped with a function named RGB. Its syntax is:

This function takes three arguments and each must hold a value between 0 and 255. The first argument represents the ratio of red of the color. The second argument represents the green ratio of the color. The last argument represents the blue of the color. After the function has been called, it produces a number whose maximum value can be 255 * 255 * 255 = 16,581,375, which represents a color.

The following code sets the font color of cell A1 to vbBlack (Black).

The following code sets the font color of cell A1 to 0 (Black).

The following code sets the font color of cell A1 to RGB(0, 0, 0) (Black).

Font Effects

Strikethrough

True if the font is struck through with a horizontal line.

The following code sets the font of cell A1 to strikethrough.

Subscript

True if the font is formatted as subscript. False by default.

The following code sets the font of cell A1 to Subscript.

Superscript

True if the font is formatted as superscript; False by default.

The following code sets the font of cell A1 to Superscript.

Border

Border Index

Using VBA you can choose to create borders for the different edges of a range of cells:

  1. xlDiagonalDown (Border running from the upper left-hand corner to the lower right of each cell in the range).
  2. xlDiagonalUp (Border running from the lower left-hand corner to the upper right of each cell in the range).
  3. xlEdgeBottom (Border at the bottom of the range).
  4. xlEdgeLeft (Border at the left-hand edge of the range).
  5. xlEdgeRight (Border at the right-hand edge of the range).
  6. xlEdgeTop (Border at the top of the range).
  7. xlInsideHorizontal (Horizontal borders for all cells in the range except borders on the outside of the range).
  8. xlInsideVertical (Vertical borders for all the cells in the range except borders on the outside of the range).

Line Style

The value of this property can be set to one of the constants: xlContinuous (Continuous line), xlDash (Dashed line), xlDashDot (Alternating dashes and dots), xlDashDotDot (Dash followed by two dots), xlDot (Dotted line), xlDouble (Double line), xlLineStyleNone (No line), xlSlantDashDot (Slanted dashes).

The following code example sets the border on the bottom edge of cell A1 with continuous line.

The following code example removes the border on the bottom edge of cell A1.

Line Thickness

The value of this property can be set to one of the constants: xlHairline (Hairline, thinnest border), xlMedium (Medium), xlThick (Thick, widest border), xlThin (Thin).

The following code example sets the thickness of the border created to xlThin (Thin).

Line Color

The value of this property can be set to one of the standard colors: vbBlack, vbRed, vbGreen, vbYellow, vbBlue, vbMagenta, vbCyan, vbWhite or an integer value from 0 to 16,581,375.

The following code example sets the color of the border on the bottom edge to green.

You can also use the RGB function to create a color value.

The following example sets the color of the bottom border of cell A1 with RGB fuction.

Pattern Style

The value of this property can be set to one of the constants:

  1. xlPatternAutomatic (Excel controls the pattern.)
  2. xlPatternChecker (Checkerboard.)
  3. xlPatternCrissCross (Criss-cross lines.)
  4. xlPatternDown (Dark diagonal lines running from the upper left to the lower right.)
  5. xlPatternGray16 (16% gray.)
  6. xlPatternGray25 (25% gray.)
  7. xlPatternGray50 (50% gray.)
  8. xlPatternGray75 (75% gray.)
  9. xlPatternGray8 (8% gray.)
  10. xlPatternGrid (Grid.)
  11. xlPatternHorizontal (Dark horizontal lines.)
  12. xlPatternLightDown (Light diagonal lines running from the upper left to the lower right.)
  13. xlPatternLightHorizontal (Light horizontal lines.)
  14. xlPatternLightUp (Light diagonal lines running from the lower left to the upper right.)
  15. xlPatternLightVertical (Light vertical bars.)
  16. xlPatternNone (No pattern.)
  17. xlPatternSemiGray75 (75% dark moiré.)
  18. xlPatternSolid (Solid color.)
  19. xlPatternUp (Dark diagonal lines running from the lower left to the upper right.)

Protection

Locking Cells

This property returns True if the object is locked, False if the object can be modified when the sheet is protected, or Null if the specified range contains both locked and unlocked cells.

The following code example unlocks cells A1:B22 on Sheet1 so that they can be modified when the sheet is protected.

Hiding Formulas

This property returns True if the formula will be hidden when the worksheet is protected, Null if the specified range contains some cells with FormulaHidden equal to True and some cells with FormulaHidden equal to False.

Don’t confuse this property with the Hidden property. The formula will not be hidden if the workbook is protected and the worksheet is not, but only if the worksheet is protected.

The following code example hides the formulas in cells A1 and C1 on Sheet1 when the worksheet is protected.

Источник

<<Lesson 15>> [Contents] <<Lesson 17>>

In this Lesson, we will explore how to write Excel VBA code that formats the color of an MS Excel spreadsheet. Using  Excel VBA code, we can change the font color as well as the background color of each cell effortlessly.

Alright, let’s create a program that can format random font and background colors using a randomizing process. Colors can be assigned using a number of methods in Excel VBA, but it is easier to use the RGB function. The RGB function has three numbers corresponding to the red, green and blue components. The range of values of the three numbers is from 0 to 255. A mixture of the three primary colors will produce different colors.

The syntax to set the font color is

cells(i,j).Font.Color=RGB(x,y,x)

where x,y, z are any numbers between 1 and 255

The syntax to set the cell’s background color is

cells(i,j).Interior.Color=RGB(x,y,x)

Where x,y, z can be any number between 1 and 255

Some RGB Color Codes are shown in the following chart,

Color RGB Code
(0,0,0)
(255,0,0)
(255,255,0)
(255,165,0)
(0,0,255)
(0,128,0)
(128,0,128)

Example 16.1

In this example, clicking the command button changes the background colors from Cells(1,1) to Cells(7,1) according to the specified RGB color codes. It also format the font colors from Cells(1,2) to cells(7,2) using specified RGB color codes.

The code

Private Sub CommandButton1_Click()
Dim i As Integer

‘To fill the cells with colors using RGB codes
Cells(1, 1).Interior.Color = RGB(0, 0, 0)
Cells(2, 1).Interior.Color = RGB(255, 0, 0)
Cells(3, 1).Interior.Color = RGB(255, 255, 0)
Cells(4, 1).Interior.Color = RGB(255, 165, 0)
Cells(5, 1).Interior.Color = RGB(0, 0, 255)
Cells(6, 1).Interior.Color = RGB(0, 128, 0)
Cells(7, 1).Interior.Color = RGB(128, 0, 128)
‘To format font color with RGB codes
For i = 1 To 7
Cells(i, 2).Value = “Font Color”
Next
Cells(1, 2).Font.Color = RGB(0, 0, 0)
Cells(2, 2).Font.Color = RGB(255, 0, 0)
Cells(3, 2).Font.Color = RGB(255, 255, 0)
Cells(4, 2).Font.Color = RGB(255, 165, 0)
Cells(5, 2).Font.Color = RGB(0, 0, 255)
Cells(6, 2).Font.Color = RGB(0, 128, 0)
Cells(7, 2).Font.Color = RGB(128, 0, 128)

End Sub

Excel VBA

Example 16.2

In this example, the font color in cells(1,1) and background color in cells(2,1) are changing for every click of the command button due to the randomized process.Rnd is a random number between 0 and 1, therefore 255* Rnd will produce a number between 0 and 255  and Int(255*Rnd) will produce integers that take the values from 0 to 254
So we need to add 1 to get random integers from 0 to 255.
For example;Rnd=0.229
255*Rnd=58.395
Int(58.395)=58

The code

Private Sub CommandButton1_Click()Randomize Timer
Dim i, j, k As Integer
i = Int(255 * Rnd) + 1
j = Int(255 * Rnd) + 1
k = Int(255 * Rnd) + 1
Cells(1, 1).Font.Color = RGB(i, j, k)
Cells(2, 1).Interior.Color = RGB(j, k, i)
End Sub

The Output

<<Lesson 15>> [Contents] <<Lesson 17>>

Formatting Cells Number

General

Range("A1").NumberFormat = "General"

Number

Range("A1").NumberFormat = "0.00"

Currency

Range("A1").NumberFormat = "$#,##0.00"

Accounting

Range("A1").NumberFormat = "_($* #,##0.00_);_($* (#,##0.00);_($* ""-""??_);_(@_)"

Date

Range("A1").NumberFormat = "yyyy-mm-dd;@"

Time

Range("A1").NumberFormat = "h:mm:ss AM/PM;@"

Percentage

Range("A1").NumberFormat = "0.00%"

Fraction

Range("A1").NumberFormat = "# ?/?"

Scientific

Range("A1").NumberFormat = "0.00E+00"

Text

Range("A1").NumberFormat = "@"

Special

Range("A1").NumberFormat = "00000"

Custom

Range("A1").NumberFormat = "$#,##0.00_);[Red]($#,##0.00)"

Formatting Cells Alignment

Text Alignment

Horizontal

The value of this property can be set to one of the constants: xlGeneral, xlCenter, xlDistributed, xlJustify, xlLeft, xlRight.

The following code sets the horizontal alignment of cell A1 to center.

Range("A1").HorizontalAlignment = xlCenter

Vertical

The value of this property can be set to one of the constants: xlBottom, xlCenter, xlDistributed, xlJustify, xlTop.

The following code sets the vertical alignment of cell A1 to bottom.

Range("A1").VerticalAlignment = xlBottom

Text Control

Wrap Text

This example formats cell A1 so that the text wraps within the cell.

Range("A1").WrapText = True

Shrink To Fit

This example causes text in row one to automatically shrink to fit in the available column width.

Rows(1).ShrinkToFit = True

Merge Cells

This example merge range A1:A4 to a large one.

Range("A1:A4").MergeCells = True

Right-to-left

Text direction

The value of this property can be set to one of the constants: xlRTL (right-to-left), xlLTR (left-to-right), or xlContext (context).

The following code example sets the reading order of cell A1 to xlRTL (right-to-left).

Range("A1").ReadingOrder = xlRTL

Orientation

The value of this property can be set to an integer value from –90 to 90 degrees or to one of the following constants: xlDownward, xlHorizontal, xlUpward, xlVertical.

The following code example sets the orientation of cell A1 to xlHorizontal.

Range("A1").Orientation = xlHorizontal

Font

Font Name

The value of this property can be set to one of the fonts: Calibri, Times new Roman, Arial

The following code sets the font name of range A1:A5 to Calibri.

Range("A1:A5").Font.Name = "Calibri"

Font Style

The value of this property can be set to one of the constants: Regular, Bold, Italic, Bold Italic.

The following code sets the font style of range A1:A5 to Italic.

Range("A1:A5").Font.FontStyle = "Italic"

Font Size

The value of this property can be set to an integer value from 1 to 409.

The following code sets the font size of cell A1 to 14.

Range("A1").Font.Size = 14

Underline

The value of this property can be set to one of the constants: xlUnderlineStyleNone, xlUnderlineStyleSingle, xlUnderlineStyleDouble, xlUnderlineStyleSingleAccounting, xlUnderlineStyleDoubleAccounting.

The following code sets the font of cell A1 to xlUnderlineStyleDouble (double underline).

Range("A1").Font.Underline = xlUnderlineStyleDouble

Font Color

The value of this property can be set to one of the standard colors: vbBlack, vbRed, vbGreen, vbYellow, vbBlue, vbMagenta, vbCyan, vbWhite or an integer value from 0 to 16,581,375.

To assist you with specifying the color of anything, the VBA is equipped with a function named RGB. Its syntax is:

Function RGB(RedValue As Byte, GreenValue As Byte, BlueValue As Byte) As long

This function takes three arguments and each must hold a value between 0 and 255. The first argument represents the ratio of red of the color. The second argument represents the green ratio of the color. The last argument represents the blue of the color. After the function has been called, it produces a number whose maximum value can be 255 * 255 * 255 = 16,581,375, which represents a color.

The following code sets the font color of cell A1 to vbBlack (Black).

Range("A1").Font.Color = vbBlack

The following code sets the font color of cell A1 to 0 (Black).

Range("A1").Font.Color = 0

The following code sets the font color of cell A1 to RGB(0, 0, 0) (Black).

Range("A1").Font.Color = RGB(0, 0, 0)

Font Effects

Strikethrough

True if the font is struck through with a horizontal line.

The following code sets the font of cell A1 to strikethrough.

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

Subscript

True if the font is formatted as subscript. False by default.

The following code sets the font of cell A1 to Subscript.

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

Superscript

True if the font is formatted as superscript; False by default.

The following code sets the font of cell A1 to Superscript.

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

Border

Border Index

Using VBA you can choose to create borders for the different edges of a range of cells:

  1. xlDiagonalDown (Border running from the upper left-hand corner to the lower right of each cell in the range).
  2. xlDiagonalUp (Border running from the lower left-hand corner to the upper right of each cell in the range).
  3. xlEdgeBottom (Border at the bottom of the range).
  4. xlEdgeLeft (Border at the left-hand edge of the range).
  5. xlEdgeRight (Border at the right-hand edge of the range).
  6. xlEdgeTop (Border at the top of the range).
  7. xlInsideHorizontal (Horizontal borders for all cells in the range except borders on the outside of the range).
  8. xlInsideVertical (Vertical borders for all the cells in the range except borders on the outside of the range).

Line Style

The value of this property can be set to one of the constants: xlContinuous (Continuous line), xlDash (Dashed line), xlDashDot (Alternating dashes and dots), xlDashDotDot (Dash followed by two dots), xlDot (Dotted line), xlDouble (Double line), xlLineStyleNone (No line), xlSlantDashDot (Slanted dashes).

The following code example sets the border on the bottom edge of cell A1 with continuous line.

Range("A1").Borders(xlEdgeBottom).LineStyle = xlContinuous

The following code example removes the border on the bottom edge of cell A1.

Range("A1").Borders(xlEdgeBottom).LineStyle = xlNone

Line Thickness

The value of this property can be set to one of the constants: xlHairline (Hairline, thinnest border), xlMedium (Medium), xlThick (Thick, widest border), xlThin (Thin).

The following code example sets the thickness of the border created to xlThin (Thin).

Range("A1").Borders(xlEdgeBottom).Weight = xlThin

Line Color

The value of this property can be set to one of the standard colors: vbBlack, vbRed, vbGreen, vbYellow, vbBlue, vbMagenta, vbCyan, vbWhite or an integer value from 0 to 16,581,375.

The following code example sets the color of the border on the bottom edge to green.

Range("A1").Borders(xlEdgeBottom).Color = vbGreen

You can also use the RGB function to create a color value.

The following example sets the color of the bottom border of cell A1 with RGB fuction.

Range("A1").Borders(xlEdgeBottom).Color = RGB(255, 0, 0)

Fill

Pattern Style

The value of this property can be set to one of the constants:

  1. xlPatternAutomatic (Excel controls the pattern.)
  2. xlPatternChecker (Checkerboard.)
  3. xlPatternCrissCross (Criss-cross lines.)
  4. xlPatternDown (Dark diagonal lines running from the upper left to the lower right.)
  5. xlPatternGray16 (16% gray.)
  6. xlPatternGray25 (25% gray.)
  7. xlPatternGray50 (50% gray.)
  8. xlPatternGray75 (75% gray.)
  9. xlPatternGray8 (8% gray.)
  10. xlPatternGrid (Grid.)
  11. xlPatternHorizontal (Dark horizontal lines.)
  12. xlPatternLightDown (Light diagonal lines running from the upper left to the lower right.)
  13. xlPatternLightHorizontal (Light horizontal lines.)
  14. xlPatternLightUp (Light diagonal lines running from the lower left to the upper right.)
  15. xlPatternLightVertical (Light vertical bars.)
  16. xlPatternNone (No pattern.)
  17. xlPatternSemiGray75 (75% dark moiré.)
  18. xlPatternSolid (Solid color.)
  19. xlPatternUp (Dark diagonal lines running from the lower left to the upper right.)

Protection

Locking Cells

This property returns True if the object is locked, False if the object can be modified when the sheet is protected, or Null if the specified range contains both locked and unlocked cells.

The following code example unlocks cells A1:B22 on Sheet1 so that they can be modified when the sheet is protected.

Worksheets("Sheet1").Range("A1:B22").Locked = False
Worksheets("Sheet1").Protect

Hiding Formulas

This property returns True if the formula will be hidden when the worksheet is protected, Null if the specified range contains some cells with FormulaHidden equal to True and some cells with FormulaHidden equal to False.

Don’t confuse this property with the Hidden property. The formula will not be hidden if the workbook is protected and the worksheet is not, but only if the worksheet is protected.

The following code example hides the formulas in cells A1 and C1 on Sheet1 when the worksheet is protected.

Worksheets("Sheet1").Range("A1:C1").FormulaHidden = True

Изменение цвета текста (шрифта) в ячейке рабочего листа 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

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

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


VBA to get Excel Cell Background Color RGB Code & Change it

Hope you would like these in-depth Excel cell color formatting techniques.

In Excel macro to get cell color in RGB code or change it, we can follow any of these methods.

  1. Excel VBA get RGB Color of Cell or Convert Cell Color to RGB Code
  2. VBA: Excel Color index to change cell color
  3. Manual: Excel Background Color of Cell

This page is all about Excel Cell formatting.

Let’s see with an example on how to play with this RGB code.

1. Excel VBA Get RGB Color of Cell

To do this, first get the color code of a cell using its Cells.Interior property.

Excel will return a hexadecimal value. Which can be to its corresponding RGB value using the formula in the vba code.

Once we are familiar with this code, then it will be easy to

  • Get the Excel color index of a cell.
  • Change cell Interior Color in VBA.
  • Change cell color based on value in another cell.
  • Count number of cells based on its color.
Sub Excel_VBA_Get_RGB_Color_Of_Cell()
    Dim cColor, cRed, cGreen, cBlue
    
    'Get Cell background color VBA Value. Convert this Color Value to RGB Value
    cColor = ActiveSheet.Cells(1, 1).Interior.Color
    
    'Convert Color Code to RGB
    cRed = (cColor Mod 256)
    cGreen = (cColor  256) Mod 256
    cBlue = (cColor  65536) Mod 256
    MsgBox cColor & "; " & VBA.RGB(cRed, cGreen, cBlue)
End Sub

Many times, we have to convert this hexadecimal to RGB code to use it in with many build in function calls. So, this Excel VBA get RGB color of cell will be much useful in many ways.

Above VBA code converts the cell color to its corresponding RGB code. The below code does the reverse.

2. Excel VBA Change Cell Color Index using RGB code

Using this Excel VBA, change cell background color.

Also if you need to get Cell background color property in a VBA variable field to use it inside a IF loop. The code below serves both the purpose.

Sub Excel_VBA_Change_Cell_Color_RGB()
    'Set Red, Green, Blue Color Coding levels
    R = 50
    G = 150
    B = 255

    'Get the Corresponding RGB Code
    Dim RGBCode As Long
    RGBCode = VBA.RGB(R, G, B)

    'Excel VBA Change Cell Color Macro Code
    Sheets(1).Cells(1, 1).Interior.Color = RGBCode
    'If a Cell color has to be changed based on another cell value, 
    'then embed the above code inside a IF condition

    'Cell Interior Color VBA
    'Cell background Color in VBA
    Sheets(1).Cells(1, 1) = Sheets(1).Cells(1, 1).Interior.Color

    'Additional Formating info
    'Similar to Background color, fond color also can be changed with below code
    'Sheets(1).Cells(1, 1).Font.Color = RGBCode

End Sub

This code can also be used to change the background color of a cell based on a cell value. It can be used as an alternative for conditional formatting.

More Tips: Looping Structure and Conditional Statements in VBA

3. Change Excel Cell Color Background or Font Color

To do this manually, we have to first select cell & change Excel color index as below

  1. Select ‘Home’ Menu.
  2. Click ‘Fill Color’ in ‘Font’ tab.
  3. Choose a color from the drop down or
  4. Right click on cell & choose Format Cells option to perform all the formatting changes

This will change the cell background color or range selected by user. But there are times, where we have to change the background color or font color based on condition within a VBA code. This can be done by using the Interior.Color property of Excel cell discussed above.

With this property the Excel Color Index, Format and Theme of an worksheet cell can be modified, during the VBA Macro runtime.

Related: Different Methods to get or update value in Excel Worksheet

4. Open VBA Color Palette

This is another method to get user input using the built in color palette in Excel.

Sub Open_Color_Palette_Set_Color()
    Dim ret As Boolean

    'Select a Cell before invoking this command.
    ThisWorkbook.Sheets(1).Cells(1, 1).Select
    'Application.Dialogs.Item(xlDialogColorPalette).Show
    'Application.CommandBars("Fill Color").Visible = True
    Application.Dialogs(xlDialogPatterns).Show
    
End Sub

This command has to select a cell within the code before opening color palette. Once executed, this code will open the color palette allowing user to choose a color. Once the color is chosen, the selected cell background will be applied with that color.

Excel VBA Cell Background Color & Formatting

We saw mainly on how to get RGB code for a cell color & change the cell background color using VBA . Once if we know how to get or set a color code through VBA, it will be easy to manipulate them inside our coding.

In addition to font and background color, we can also do the below list of cell formatting operations.

  1. Wrap Text.
    • Sheets(1).Cells(1, 1).WrapText = True
  2. Alignment
    • Sheets(1).Cells(1, 1).HorizontalAlignment = xlCenter
  3. Font Change
    • Sheets(1).Cells(1, 1).Font.Name = “Arial”
  4. Font Size
    • Sheets(1).Cells(1, 1).Font.Size = 12
  5. Autofit
    • Columns(“A:A”).EntireColumn.AutoFit
  6. Font Bold or Italic
    • Sheets(1).Cells(1, 1).Font.Italic = True

There are plenty of such option available to change the format of a cell. We can try to record macro while manually doing formatting changes and get the corresponding code to perform these Formatting.

Additional Reference on Cell Color & Interior Property

  • http://office.microsoft.com/en-in/excel-help/change-cell-background-color-using-vba-HA001136627.aspx
  • http://stackoverflow.com/questions/365125/how-do-i-set-the-background-color-of-excel-cells-using-vba
  • http://msdn.microsoft.com/en-us/library/office/ff837616(v=office.15).aspx

Понравилась статья? Поделить с друзьями:
  • Format codes for excel
  • Format characters in word
  • Format cells microsoft excel
  • Format cells in excel with vba
  • Format cells excel это