Merge table cells across columns but skip if column don't exist
I have a Word doc with tables of various column counts.
I am working on a macro that loops through every table's row 1 and merges cells in column 2 and 3, 3 and 4, 4 and 5, etc. That part works fine.
My problem comes with tables that don't have that many columns. I tried adding in an if statement along the lines of if there are more than X columns, continue, but get an error that an object is required when it gets to this line: If Tbl.Columns.Count > 3 Then
I'm trying to learn VBA but am not sure what the problem is. Thanks!
Sub MergeCells2()
For Each Tbl In ActiveDocument.Tables
Tbl.Cell(1, 2).Merge (Tbl.Cell(1, 3))
Next
If Tbl.Columns.Count > 3 Then
For Each Tbl In ActiveDocument.Tables
Tbl.Cell(1, 3).Merge (Tbl.Cell(1, 4))
Next
End If
If Tbl.Columns.Count > 4 Then
For Each Tbl In ActiveDocument.Tables
Tbl.Cell(1, 4).Merge (Tbl.Cell(1, 5))
Next
End If
If Tbl.Columns.Count > 5 Then
For Each Tbl In ActiveDocument.Tables
Tbl.Cell(1, 5).Merge (Tbl.Cell(1, 6))
Next
End If
If Tbl.Columns.Count > 6 Then
For Each Tbl In ActiveDocument.Tables
Tbl.Cell(1, 6).Merge (Tbl.Cell(1, 7))
Next
End If
If Tbl.Columns.Count > 7 Then
For Each Tbl In ActiveDocument.Tables
Tbl.Cell(1, 7).Merge (Tbl.Cell(1, 8))
Next
End If
If Tbl.Columns.Count > 8 Then
For Each Tbl In ActiveDocument.Tables
Tbl.Cell(1, 8).Merge (Tbl.Cell(1, 9))
Next
End If
End Sub
|