This expands your code so that it works for the entire table if the table as a whole is selected (selection type pbSelectionShape and shape type pbTable) and for the entire cell if the selection is of type pbSelectionText.
The trick for the latter functionality is that the .ContainingObject refers to the entire Shape, and that every Table Shape consists of one Story object. The .Start and .End properties of a TextRange object refer to its position within it's Story object. By comparing these two properties, we are able to identify which cell the selected text belongs to (it is not possible in Publisher to simultaneously select a little bit of text in several different cells).
Before I figured out this approach, I tried to call .Parent until TypeName() would equal "Cell", but this wouldn't work because the .Parent for Selection.TextRange is Selection (and not the Parent in the document itself as I had hoped)
Option Explicit
Sub InvertSquare()
ActiveDocument.BeginCustomUndoAction "Invert square"
Dim oCell As Cell
Dim oShape As Shape
If selection.Type = pbSelectionTableCells Then
Debug.Print "Table cells"
For Each oCell In selection.TableCellRange
SetInvertedColors oCell
Next oCell
ElseIf selection.Type = pbSelectionText Then
Debug.Print "Text"
Dim selText As TextRange
Dim x As Variant
Set selText = selection.TextRange
Set x = selText.ContainingObject
If TypeName(x) = "Shape" Then
If x.Type = pbTable Then
For Each oCell In x.Table.Cells
If oCell.HasText Then
If oCell.TextRange.Start <= selText.Start Then
If oCell.TextRange.End >= selText.End Then
SetInvertedColors oCell
Exit For
End If
End If
End If
Next oCell
End If
End If
ElseIf selection.Type = pbSelectionShape Then
Debug.Print "ShapeRange"
Dim oShapes As ShapeRange
Set oShapes = selection.ShapeRange
For Each oShape In oShapes
If oShape.Type = pbTable Then
For Each oCell In selection.TableCellRange
SetInvertedColors oCell
Next oCell
Exit For
End If
Next oShape
Debug.Print "Shape"
End If
ActiveDocument.BeginCustomUndoAction "Invert square"
End Sub
Sub SetInvertedColors(oCell As Cell)
Debug.Print oCell.TextRange.Text
oCell.TextRange.Font.Color = RGB(255, 255, 255)
''oCell.Fill.ForeColor.RGB = RGB(0, 0, 0) ''Out of memory error for whatever reason
End Sub
For some reason, I get an out of memory error when I try to set the .ForeColor.RGB in Publisher, but this happens with your code for me too, so I'm hoping that it works for you anyway if you uncomment the second last line.