Word vba cell color

I am trying to set up a new table at the end of my document and format it to my specifications. But the backgroundcolor and the textcolor do not seem to work. The Font size also is not exactly what I want, since it applies to the whole table and not only one cell.

This is what I have so far:

Dim myRange As Object
Set myRange = ActiveDocument.Content
myRange.Collapse Direction:=wdCollapseEnd
ActiveDocument.Tables.Add Range:=myRange, NumRows:=3, NumColumns:=2
With .Tables(.Tables.Count)
    .Cell(1, 1).Select
    With Selection
        .Shading.Texture = wdTextureNone
        .Shading.ForegroundPatternColor = wdColorWhite
        .Shading.BackgroundPatternColor = wdColorGray25
        .Font.Size = 14
        .Font.Bold = True
        .Text = "Hello World"
    End With
End With

I want the first row of the table without borders and with font 14, bold, white text on gray background.

asked Aug 14, 2015 at 12:36

Kazschuri's user avatar

KazschuriKazschuri

5601 gold badge4 silver badges18 bronze badges

0

I found the Answer.

The solution is as follows:

With .Tables(.Tables.Count)        
    With .Cell(1, 1)
        .Shading.BackgroundPatternColor = wdColorGray50
        With .Range
            With .Font 
                .TextColor = wdColorWhite
                .Size = 18
                .Bold = True
            End With
            .Text = "Hello World"
        End With
    End With            
End With

I removed the selection of the cell and used it directly. But the real thing was, the use of .Range when applying .Font and .Text

ak112358's user avatar

ak112358

7032 gold badges13 silver badges25 bronze badges

answered Aug 18, 2015 at 7:24

Kazschuri's user avatar

KazschuriKazschuri

5601 gold badge4 silver badges18 bronze badges

INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Contact US

Thanks. We have received your request and will respond promptly.

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!

  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It’s Free!

*Tek-Tips’s functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Macro to Change Table Cell Colors in Word

Macro to Change Table Cell Colors in Word

(OP)

22 May 06 14:39

Is it possible to use a macro to change the color of cells in a Word table based on what text is in the cell?  For example, change color to blue if «BLUE» is in there, red for «RED,» yellow for «YELLOW,» and green for «GREEN.»

Thanks!

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Join Tek-Tips® Today!

Join your peers on the Internet’s largest technical computer professional community.
It’s easy to join and it’s free.

Here’s Why Members Love Tek-Tips Forums:

  • Tek-Tips ForumsTalk To Other Members
  • Notification Of Responses To Questions
  • Favorite Forums One Click Access
  • Keyword Search Of All Posts, And More…

Register now while it’s still free!

Already a member? Close this window and log in.

Join Us             Close

Содержание

  • 1 Color cells
  • 2 Coloring all negative cells» backgrounds red
  • 3 Color multiple-column ranges
  • 4 Make a Cell font bold based on the cell value
  • 5 Makes cell background red if the value is negative
  • 6 Make the font in number cell bold
  • 7 Removes all borders for the selected cells
  • 8 Set cell color
  • 9 Set data to cell D1 of the selected worksheet. And format its contents with color and borders.
  • 10 Sets just the color of cell C1 to red.
  • 11 the font color of all cells in the active worksheet is set to red

Color cells

   <source lang="vb">

Public Sub ColorCells()

 Dim Sales As Range
 Dim i As Long
 Dim j As Long
 
 Set Sales = Range("SalesData")
 For i = 1 To Sales.Rows.Count
   For j = 1 To Sales.Columns.Count
     If Sales.Cells(i, j).Value < 100 Then
       Sales.Cells(i, j).Font.ColorIndex = 3
     Else
       Sales.Cells(i, j).Font.ColorIndex = 1
     End If
   Next j
 Next i

End Sub

</source>
   
  

Coloring all negative cells» backgrounds red

   <source lang="vb">

Sub SelectiveColor1()

   If TypeName(Selection) <> "Range" Then Exit Sub
   Const REDINDEX = 3
   Application.ScreenUpdating = False
   For Each Cell In Selection
       If Cell.value < 0 Then
         Cell.Interior.ColorIndex = REDINDEX
       Else
         Cell.Interior.ColorIndex = xlNone
       End If
   Next Cell

End Sub

</source>
   
  

Color multiple-column ranges

   <source lang="vb">

Sub SelectiveColor2()

   Dim FormulaCells As range
   Dim ConstantCells As range
   Const REDINDEX = 3
   On Error Resume Next
   Application.ScreenUpdating = False
   Set FormulaCells = Selection.SpecialCells(xlFormulas, xlNumbers)
   Set ConstantCells = Selection.SpecialCells(xlConstants, xlNumbers)
   For Each Cell In FormulaCells
       If Cell.value < 0 Then _
         Cell.Font.ColorIndex = REDINDEX
   Next Cell
   For Each Cell In ConstantCells
       If Cell.value < 0 Then
          Cell.Interior.ColorIndex = REDINDEX
       Else
          Cell.Interior.ColorIndex = xlNone
       End If
   Next Cell

End Sub

</source>
   
  

Make a Cell font bold based on the cell value

   <source lang="vb">

Sub valueDemo()

    If ActiveCell.value = 10 Then
       ActiveCell.font.bold = True
    End If

End Sub

</source>
   
  

Makes cell background red if the value is negative

   <source lang="vb">

Sub SelectiveColor2()

   Dim FormulaCells As Range
   Dim ConstantCells As Range
   Const REDINDEX = 3
   On Error Resume Next
   Application.ScreenUpdating = False
   Set FormulaCells = Selection.SpecialCells (xlFormulas, xlNumbers)
   Set ConstantCells = Selection.SpecialCells (xlConstants, xlNumbers)
   For Each cell In FormulaCells
       If cell.Value < 0 Then _
         cell.Font.ColorIndex = REDINDEX
   Next cell
   For Each cell In ConstantCells
       If cell.Value < 0 Then
          cell.Interior.ColorIndex = REDINDEX
       Else
          cell.Interior.ColorIndex = xlNone
       End If
   Next cell

End Sub

</source>
   
  

Make the font in number cell bold

   <source lang="vb">

Sub BoldNCRows()

 Dim rngRow As Range
 For Each rngRow In Cells.SpecialCells(xlCellTypeConstants, xlNumbers).Rows
   rngRow.Font.Bold = True
 Next rngRow

End Sub

</source>
   
  

Removes all borders for the selected cells

   <source lang="vb">

Sub RemoveAllBorders()

 Dim calcModus&, updateModus&, i
 Dim rng As Range, ar As Range
 Dim brd As Border
 If Selection Is Nothing Then Exit Sub
 
 calcModus = Application.Calculation
 updateModus = Application.ScreenUpdating
 Application.Calculation = xlManual
 Application.ScreenUpdating = False
 For Each ar In Selection.Areas   
   For Each rng In ar             
     For Each i In Array(xlEdgeTop, xlEdgeBottom, xlEdgeLeft, xlEdgeRight, xlDiagonalDown, xlDiagonalUp)
       rng.Borders(i).LineStyle = xlLineStyleNone
     Next i
     If rng.Column > 1 Then
       rng.Offset(0, -1).Borders(xlRight).LineStyle = xlLineStyleNone
     End If
     If rng.Column < 256 Then
        rng.Offset(0, 1).Borders(xlLeft).LineStyle = xlLineStyleNone
     End If
     If rng.Row > 1 Then
       rng.Offset(-1, 0).Borders(xlBottom).LineStyle = xlLineStyleNone
     End If
     If rng.Row < 65536 Then
        rng.Offset(1, 0).Borders(xlTop).LineStyle = xlLineStyleNone
     End If
   Next rng
 Next ar
 Application.Calculation = calcModus
 Application.ScreenUpdating = updateModus

End Sub

</source>
   
  

Set cell color

   <source lang="vb">

Sub Set_Protection()

   On Error GoTo errorHandler
   Dim myDoc As Worksheet
   Dim cel As Range
   Set myDoc = ActiveSheet
   myDoc.Unprotect
   For Each cel In myDoc.UsedRange
       cel.Locked = True
       cel.Font.ColorIndex = xlColorIndexAutomatic
   Next
   myDoc.Protect
   Exit Sub
   errorHandler:
   MsgBox Error

End Sub

</source>
   
  

Set data to cell D1 of the selected worksheet. And format its contents with color and borders.

   <source lang="vb">

Sub cmd()

   Cells(1, "D").Value = "Text"
   Cells(1, "D").Select
   
   With Selection
       .Font.Bold = True
       .Font.Name = "Arial"
       .Font.Size = 72
       .Font.Color = RGB(0, 0, 255)  "Dark blue
       .Columns.AutoFit
       .Interior.Color = RGB(0, 255, 255) "Cyan
       .Borders.Weight = xlThick
       .Borders.Color = RGB(0, 0, 255)  "Dark Blue
   End With

End Sub

</source>
   
  

Sets just the color of cell C1 to red.

   <source lang="vb">

Sub cellFont()

   Cells(1, "C").Font.Color = vbRed

End Sub

</source>
   
  

the font color of all cells in the active worksheet is set to red

   <source lang="vb">

Sub fontColor()

   Cells.Font.Color = vbRed

End Sub

</source>

Word VBA always has refused to deal with rows in a table that contains vertically merged cells, or with columns in a table that contains horizontally merged cells. If your table has only vertically merged cells, you can run the For Each on the columns instead of the rows, like this:

Code:

Sub test()
    Dim tbl As Table
    Dim col As Column
    Dim cel As Cell
    
    For Each tbl In ActiveDocument.Tables
        For Each col In tbl.Columns
            For Each cel In col.Cells
                If cel.Shading.BackgroundPatternColor = RGB(225, 225, 153) Then
                    cel.Shading.BackgroundPatternColor = RGB(225, 225, 225)
                End If
            Next cel
        Next col
    Next tbl
End Sub

Another alternative is to go through all cells in the table’s Range, like this:

Code:

Sub test()
    Dim tbl As Table
    Dim cel As Cell
    
    For Each tbl In ActiveDocument.Tables
        For Each cel In tbl.Range.Cells
            If cel.Shading.BackgroundPatternColor = RGB(225, 225, 153) Then
                cel.Shading.BackgroundPatternColor = RGB(225, 225, 225)
            End If
        Next cel
    Next tbl
End Sub

Either way, you could run into this problem: If the RGB(225, 225, 153) shading was applied after the cells were merged, then VBA will tell you that the BackgroundPatternColor of the merged cells is -1 instead of the actual RGB value, and the If statement will see the condition as False. That happens because only one of the cells that were merged together has the shading you expect, and the others are not shaded. The only way to avoid that is to unmerge, shade all of the cells that will be included, and then merge them again.

Заливка ячейки цветом в VBA Excel. Фон ячейки. Свойства .Interior.Color и .Interior.ColorIndex. Цветовая модель RGB. Стандартная палитра. Очистка фона ячейки.

Свойство .Interior.Color объекта Range

Начиная с Excel 2007 основным способом заливки диапазона или отдельной ячейки цветом (зарисовки, добавления, изменения фона) является использование свойства .Interior.Color объекта Range путем присваивания ему значения цвета в виде десятичного числа от 0 до 16777215 (всего 16777216 цветов).

Заливка ячейки цветом в VBA Excel

Пример кода 1:

Sub ColorTest1()

Range(«A1»).Interior.Color = 31569

Range(«A4:D8»).Interior.Color = 4569325

Range(«C12:D17»).Cells(4).Interior.Color = 568569

Cells(3, 6).Interior.Color = 12659

End Sub

Поместите пример кода в свой программный модуль и нажмите кнопку на панели инструментов «Run Sub» или на клавиатуре «F5», курсор должен быть внутри выполняемой программы. На активном листе Excel ячейки и диапазон, выбранные в коде, окрасятся в соответствующие цвета.

Есть один интересный нюанс: если присвоить свойству .Interior.Color отрицательное значение от -16777215 до -1, то цвет будет соответствовать значению, равному сумме максимального значения палитры (16777215) и присвоенного отрицательного значения. Например, заливка всех трех ячеек после выполнения следующего кода будет одинакова:

Sub ColorTest11()

Cells(1, 1).Interior.Color = 12207890

Cells(2, 1).Interior.Color = 16777215 + (12207890)

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

End Sub

Проверено в Excel 2016.

Вывод сообщений о числовых значениях цветов

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

Пример кода 2:

Sub ColorTest2()

MsgBox Range(«A1»).Interior.Color

MsgBox Range(«A4:D8»).Interior.Color

MsgBox Range(«C12:D17»).Cells(4).Interior.Color

MsgBox Cells(3, 6).Interior.Color

End Sub

Вместо вывода сообщений можно присвоить числовые значения цветов переменным, объявив их как Long.

Использование предопределенных констант

В VBA Excel есть предопределенные константы часто используемых цветов для заливки ячеек:

Предопределенная константа Наименование цвета
vbBlack Черный
vbBlue Голубой
vbCyan Бирюзовый
vbGreen Зеленый
vbMagenta Пурпурный
vbRed Красный
vbWhite Белый
vbYellow Желтый
xlNone Нет заливки

Присваивается цвет ячейке предопределенной константой в VBA Excel точно так же, как и числовым значением:

Пример кода 3:

Range(«A1»).Interior.Color = vbGreen

Цветовая модель RGB

Цветовая система RGB представляет собой комбинацию различных по интенсивности основных трех цветов: красного, зеленого и синего. Они могут принимать значения от 0 до 255. Если все значения равны 0 — это черный цвет, если все значения равны 255 — это белый цвет.

Выбрать цвет и узнать его значения RGB можно с помощью палитры Excel:

Палитра Excel

Палитра Excel

Чтобы можно было присвоить ячейке или диапазону цвет с помощью значений RGB, их необходимо перевести в десятичное число, обозначающее цвет. Для этого существует функция VBA Excel, которая так и называется — RGB.

Пример кода 4:

Range(«A1»).Interior.Color = RGB(100, 150, 200)

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

Очистка ячейки (диапазона) от заливки

Для очистки ячейки (диапазона) от заливки используется константа xlNone:

Range(«A1»).Interior.Color = xlNone

Свойство .Interior.ColorIndex объекта Range

До появления Excel 2007 существовала только ограниченная палитра для заливки ячеек фоном, состоявшая из 56 цветов, которая сохранилась и в настоящее время. Каждому цвету в этой палитре присвоен индекс от 1 до 56. Присвоить цвет ячейке по индексу или вывести сообщение о нем можно с помощью свойства .Interior.ColorIndex:

Пример кода 5:

Range(«A1»).Interior.ColorIndex = 8

MsgBox Range(«A1»).Interior.ColorIndex

Просмотреть ограниченную палитру для заливки ячеек фоном можно, запустив в VBA Excel простейший макрос:

Пример кода 6:

Sub ColorIndex()

Dim i As Byte

For i = 1 To 56

Cells(i, 1).Interior.ColorIndex = i

Next

End Sub

Номера строк активного листа от 1 до 56 будут соответствовать индексу цвета, а ячейка в первом столбце будет залита соответствующим индексу фоном.

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


Return to VBA Code Examples

This tutorial will demonstrate how to change a cell’s background color using VBA.

Change Cell Background Color with Interior.colorindex

To change a cell’s background color using VBA you can use the Interior.Colorindex property. Here’s a couple ways to change the background color of cell A1.

An example using the Range() method:

Range("A1").Interior.ColorIndex = 5

An example using the Cells() method:

Cells(1, 1).Interior.ColorIndex = 15

Need an easy way to determine what number equals what color? Check out Color Reference For Colorindex.

vba-free-addin

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.

(No installation required!)

Free Download

Понравилась статья? Поделить с друзьями:
  • Word vba all open documents
  • Word vba макрос как запустить
  • Word vba выделить текст в таблице
  • Word vba выделить строку таблицы
  • Word vba выделить найденный текст