Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Macro to Change Table Cell Colors in Word

Status
Not open for further replies.

CCHall

IS-IT--Management
May 3, 2005
46
US
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!


 
CCHAll,
This code snipit assumes the first table created in the document and uses a [tt]Like[/tt] clause to account for the special characters contained in the cell.
Code:
Sub ColorTable()
Dim MyTable As Table
Dim MyRow As Row
Dim MyCell As Cell
Set MyTable = ActiveDocument.Tables(1)
For Each MyRow In MyTable.Rows
  For Each MyCell In MyRow.Cells
    If MyCell.Range.Text Like "Blue*" Then
      MyCell.Shading.BackgroundPatternColor = wdColorBlue
    ElseIf MyCell.Range.Text Like "Red*" Then
      MyCell.Shading.BackgroundPatternColor = wdColorRed
    ElseIf MyCell.Range.Text Like "Yellow*" Then
      MyCell.Shading.BackgroundPatternColor = wdColorYellow
    ElseIf MyCell.Range.Text Like "Green*" Then
      MyCell.Shading.BackgroundPatternColor = wdColorGreen
    End If
  Next MyCell
Next MyRow
Set MyCell = Nothing
Set MyRow = Nothing
Set MyTable = Nothing
End Sub

Hope this helps,
CMP

(GMT-07:00) Mountain Time (US & Canada)
 
Just want to point out that the code above would make a cell blue (for example) only if the word "blue" was Blue - ie. Uppercase b.

"blue" would NOT make the cell blue.

"lue*" will make either "Blue", or "blue" work.

Gerry
 
Ooops, the full delimiter (to get any combination of "blue" (Upper or Lower case) should be:

"[B-b][L-l][U-u][E-e]*"

Gerry
 

What Gerry means, of course, is [blue][Bb][Ll][Uu][Ee][/blue]

Enjoy,
Tony

--------------------------------------------------------------------------------------------
We want to help you; help us to do it by reading this: Before you ask a question.
Excel VBA Training and more Help at VBAExpress[
 
Another way:
If InStr(1, MyCell.Range.Text, "Blue", vbTextCompare) = 1 Then

Or:
If InStr(1, MyCell.Range.Text, "Blue", vbTextCompare) > 0 Then

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
Yeah I should have included that, since it's Word I always use [tt]Option Compare Text[/tt] in the global declarations.

As [navy]PHV[/navy] pointed out [tt]InStr()[/tt] works as well.

CMP

(GMT-07:00) Mountain Time (US & Canada)
 
Thanks very much for the help!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top