Search code examples
vbacpu-wordword-contentcontrol

Word VBA for giving Background Color of table cell where ContentControl placed in Repeating Content Control


I have a table in Word built from repeating section content control. There are text content controls in cells of repeating section of CC.

I am able to give font color based on the text; but I couldn't change the shading of the cell except the last row.

In debug session, whether I see correct row and column number, Shading.BackgroundPatternColor does not change the color. Surprisingly, it works on the last row of the table.

Dim CC As ContentControl
Dim TableNum As Long, RowNum As Long, ColNum As Long

For Each CC In ActiveDocument.ContentControls
    If CC.Tag = "tagPriority" Then
        If CC.Range.Text = "Critical" Then
            CC.Range.Font.TextColor = wdColorAutomatic
            If CC.Range.Information(wdWithInTable) Then
                  TableNum = Me.Range(0, CC.Range.End).Tables.Count
                  RowNum = CC.Range.Information(wdStartOfRangeRowNumber)
                  ColNum = CC.Range.Information(wdStartOfRangeColumnNumber)
                  ActiveDocument.Tables(TableNum).Cell(RowNum, ColNum).Shading.BackgroundPatternColor = wdColorDarkRed
             End If
             ...

Also, I got help from the code in stackoverflow


Solution

  • After changing

    TableNum = Me.Range(0, CC.Range.End).Tables.Count
    

    to

    TableNum = ActiveDocument.Range(0, CC.Range.End).Tables.Count
    

    it worked for me. I put your code in a standard module so YMMV if you have your code in a document event handler in the ThisDocument module.

    Of course there is another method to get the table which also works

    Dim tbl As Table
    Set tbl = CC.Range.Tables(1)
    tbl.Cell(RowNum, ColNum).Shading.BackgroundPatternColor = wdColorDarkRed
    

    EDIT: The code I used:

    Sub AddCellShading()
       Dim CC As ContentControl
       Dim tbl As Table, RowNum As Long, ColNum As Long
    
       For Each CC In ActiveDocument.ContentControls
          If CC.Tag = "tagPriority" Then
             If CC.Range.Text = "Critical" Then
                CC.Range.Font.TextColor = wdColorAutomatic
                If CC.Range.Information(wdWithInTable) Then
                   Set tbl = CC.Range.Tables(1)
                   RowNum = CC.Range.Information(wdStartOfRangeRowNumber)
                   ColNum = CC.Range.Information(wdStartOfRangeColumnNumber)
                   tbl.Cell(RowNum, ColNum).Shading.BackgroundPatternColor = wdColorDarkRed
                End If
             End If
          End If
       Next CC
    End Sub
    

    The result: enter image description here