Tables with Merged Cells

G

Gerald Perna

Two weeks ago an MVP (Doug Robbins) gave me this code for
adding the name of the paragraph style in the cells of
tables. It works very well but I just noticed that it
doesn't work in tables with merged cells.

Is there any way to get around that?

Thanks.

Jerry


For i = 1 To ActiveDocument.Tables.Count
For j = 1 To ActiveDocument.Tables(i).Rows.Count
For k = 1 To ActiveDocument.Tables(i).Columns.Count
ActiveDocument.Tables(i).Cell(j,
k).Range.InsertBefore "{" & ActiveDocument.Tables(i).Cell
(j, k).Range.Paragraphs(1).Style & "}" & vbCr
Next k
Next j
Next i
 
J

Jay Freedman

Hi, Jerry,

In a table that contains merged cells, depending on whether they're merged
vertically or horizontally, one of .Rows.Count or .Columns.Count is going to
fail because there is no one answer, so VBA throws an error. The best way
around that is to run a Do...Until loop instead, using the .Next method of a
Cell object. Here's the equivalent macro:

Sub foo()
Dim oCell As Cell
Dim i As Integer

For i = 1 To ActiveDocument.Tables.Count
Set oCell = ActiveDocument.Tables(i).Cell(1, 1)
Do
oCell.Range.InsertBefore "{" & _
oCell.Range.Paragraphs(1).Style & _
"}" & vbCr
Set oCell = oCell.Next
Loop Until oCell Is Nothing
Next i
End Sub
 
H

Helmut Weber

Hi Gerald,
AFAIK, columns.count gives you the maximum number of
columns in all rows of a table. If there is a merged cell
in a row, a column is missing, therefore not adressable.
You have to calculate the numbers of columns in each row
individually.
Greetings from Bavaria, Germany
Helmut Weber
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top