In Word 2016 VBA I want to set the shading of each cell of a table with a loop. This seems to work for tables up to a size of about 15*15. With tables such as 20*20 or larger Word does not respond any more. Program execution seems to be correct though when using single step. I tried this for tables of ca. 50*50. ScreenRefresh and ScreenUpdating seem to have no influence. In the code example, setting the shading of each cell to the same background color is only for demonstration, finally I want to apply more complex settings.
Sub TableCells_SetBackgroundColors()
' Set background color for each cell in Word table
' Application does not respond if table is larger than about 20*20
' debug single step works in any case
'Application.ScreenUpdating = False
Dim i, k, cntCol, cntRow As Integer
cntCol = 15 ' 20 is not ok
cntRow = 15 ' 20 is not ok
If ActiveDocument.Tables.Count <> 0 Then
ActiveDocument.Tables(1).Delete
End If
ActiveDocument.Tables.Add Range:=Selection.Range, _
numRows:=cntRow, _
NumColumns:=cntCol
Dim myTable As Word.Table
Set myTable = Selection.Tables(1)
With myTable.Borders
.InsideLineStyle = wdLineStyleSingle
.OutsideLineStyle = wdLineStyleSingle
End With
For i = 1 To cntRow Step 1
For k = 1 To cntCol Step 1
myTable.Cell(i, k).Shading.BackgroundPatternColor = wdColorRed
'Application.ScreenRefresh
Next k
Next i
'Application.ScreenUpdating = True
End Sub