Hey there
However, if anyone has a simplified approach I would be interested.
Since you asked, here's one ;-)
(for a commented version, see bottom of posting)
' checks if selection is inside a table and stops if not
Sub formatTableAsCheckerBoard()
If Not Selection.Information(wdWithInTable) Then
MsgBox "Select a table before running this macro"
Exit Sub
End If
Call formatColouredTable(Array(wdBlack, wdWhite))
End Sub
' formats the selected table according to the given colors
Sub formatColouredTable(colors As Variant)
Dim acCell As Cell
Dim numColors As Long
Dim i As Long
If Not IsArray(colors) Then Exit Sub
numColors = UBound(colors) - LBound(colors) + 1
i = 0
For Each acCell In Selection.Tables(1).Range.Cells
acCell.Shading.BackgroundPatternColorIndex = _
colors(i Mod numColors)
i = i + 1
Next
End Sub
' Resets the background of the selected table
Sub ResetTableBG()
Dim acCell As Cell
For Each acCell In Selection.Tables(1).Range.Cells
acCell.Shading.BackgroundPatternColorIndex = wdNone
Next
End Sub
Note that with such a generalized solution, you can
easily apply other coloring patterns, like e.g. Red, White, Blue:
Call formatColouredTable(Array(wdRed, wdWhite, wdBlue))
Cheers,
Martin
---------------------------------------
' commented version:
' checks if selection is inside a table and stops if not
Sub formatColouredTable(colors As Variant)
Dim acCell As Cell
Dim numColors As Long
Dim i As Long
' only run this sub if an array was given
If Not IsArray(colors) Then Exit Sub
numColors = UBound(colors) - LBound(colors) + 1
i = 0
For Each acCell In Selection.Tables(1).Range.Cells
' use the colours of the given array one after
' the other (achieved through the use of the
' modulo operator)
' NOTE: this works also for more colors than
' just 2
acCell.Shading.BackgroundPatternColorIndex = _
colors(i Mod numColors)
i = i + 1
Next
End Sub
' formats the selected table according to the given colors
Sub formatTableAsCheckerBoard()
' check if a table was selected
If Not Selection.Information(wdWithInTable) Then
' No? --> inform user and stop
MsgBox "Select a table before running this macro"
Exit Sub
End If
' format the selected table using a Black and White
' (checkerboard) pattern
Call formatColouredTable(Array(wdBlack, wdWhite))
End Sub
' Resets the background of the selected table
Sub ResetTableBG()
Dim acCell As Cell
For Each acCell In Selection.Tables(1).Range.Cells
acCell.Shading.BackgroundPatternColorIndex = wdNone
Next
End Sub