vbams-wordword-table

Change background colour of column of word table when text is PH using a macro


I am having trouble in developing a macro to look through a word document and change the background colour columns in a table.

The macro needs to look at each table in the word document, and if a cell has the text 'PH' then the column of that cell needs to change the background colour.

It's been a while since I used VB. I've tried cell.range too as well as Selection.Find below but just keep getting errors.

Private Sub Document_Open()

Dim Tbl As Table
Dim Cel As Cell
Dim Rw As Row
Dim Col As Columns

For Each Tbl In ActiveDocument.Tables
  Set Col = Tbl.Columns
  For Each c In Col

    With Selection.Find
     .Execute FindText:="Public Holiday"
     c.Shading.BackgroundPatternColorIndex = wdRed
    End With   
  Next
Next

End Sub

Solution

  • Tested

    Dim Tbl As Table
    Dim i As Integer, j As Integer
    
    For Each Tbl In ActiveDocument.Tables
    
        For j = 1 To Tbl.Columns.Count
    
            For i = 1 To Tbl.Rows.Count
    
                If InStr(1, Tbl.Cell(i, j).Range.Text, "PH") Then Tbl.Columns(j).Shading.BackgroundPatternColor = -738132122
    
            Next
    
        Next
    
    Next
    

    Looping through each cell and checking if it contains "PH", if yes then colouring that column.