Search code examples
vbams-wordword-2010

Set the color of a table cell depending on the content


I'm trying to write a VBA code in MS Word 2016 in order to fill cells containing a certain string ("–" in my case). I have tried something like this:

Sub CellsColorFill()
    Dim tTable As Table
    Dim cCell As Cell

    For Each tTable In ActiveDocument.Range.Tables
        For Each cCell In tTable.Range.Cells
            If cCell.Range = "-" Then
                Selection.Shading.Texture = wdTextureNone
                Selection.Shading.ForegroundPatternColor = wdColorAutomatic
                Selection.Shading.BackgroundPatternColor = -603923969
            End If
        Next
    Next
    Set oCell = Nothing
    Set tTable = Nothing
End Sub

However, for some reason, it has no effect when executed. How could this task be done?


Solution

  • Note - It is good to have Option Explicit at the top of the module to help you point out undeclared variable. oCell is not declared and I assume it's a typo of cCell

    To check if a string contains a certain string, you can use InStr to check if returns a non-0 value (0 means not found)

    Option Explicit
    
    Sub CellsColorFill()
        Dim tTable As Table
        Dim cCell As Cell
    
        For Each tTable In ActiveDocument.Range.Tables
            For Each cCell In tTable.Range.Cells
                If InStr(cCell.Range.Text, "-") <> 0 Then
                    cCell.Shading.Texture = wdTextureNone
                    cCell.Shading.ForegroundPatternColor = wdColorAutomatic
                    cCell.Shading.BackgroundPatternColor = -603923969
                End If
            Next
        Next
    End Sub