We help IT Professionals succeed at work.

vb script equalizing width of rows

Keith McElroy
Keith McElroy asked
I have tables that are 6 columns in most rows and 1 merged column in other rows
I am deleting the 6th column if it exists.
Then, I want the one merged column row to be the same width.
The following code errs saying trw.width is not a valid property

How do I fix this code...

                        dim tblwidth
                        if tbl.Columns.count > 5 and then
                              for each trw in tbl.rows
                                    if trw.cells.count > 5 then
                                          trw.cells(6).Delete   'this works
                                          tblwidth = trw.width       'this fails
                                    end if
                                    if trw.cells.count = 1 then
                                          trw.width = tblwidth  'this will make the merged column row same width as the rows above that were trimmed down to 5 columns.
                                    end if
                        end if
Watch Question

Consultant and developer
Try this. It adds the widths of the five remaining cells after you have deleted the last one to create your "tblWidth" variable.

NB that this will not work if the FIRST row has a merged cell.

Sub fixTables()
Dim tblWidth As Double
Dim tbl As Table, trw As Row
Dim i As Long

For Each tbl In ActiveDocument.Tables
If tbl.Columns.Count > 5 Then
For Each trw In tbl.Rows
If trw.Cells.Count = 6 Then
tblWidth = 0
 'add widths of remaining cells to create tblwidth
 For i = 1 To 5
 tblWidth = tblWidth + trw.Cells(i).Width
 End If
 If trw.Cells.Count = 1 Then
 trw.Cells.Width = tblWidth
 End If
End If

End Sub

Open in new window