PDA

View Full Version : Insert Table "Centered" in Parent Table Cell



gmaxey
12-23-2012, 09:42 AM
This is really kicking my butt!!:help

In Word 2003/2007/2010/2013 I'm am seeing the following behaviour when I attempt to programtically insert a nested table "centered" in a parent table cell:

Sub ScratchMacro()
Dim oTbl As Word.Table
Dim oCell As Word.Cell
Dim oRng As Word.Range
Dim oTblInsert As Word.Table
Set oTbl = ActiveDocument.Tables.Add(Selection.Range, 1, 2)
'Alignment - Returns 0 (Left aligned)
Debug.Print oTbl.Cell(1, 1).Range.ParagraphFormat.Alignment
For Each oCell In oTbl.Rows(1).Range.Cells
oCell.Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
oCell.VerticalAlignment = wdCellAlignVerticalCenter
Next oCell
'Alignment - Returns 1 (Center aligned)
Debug.Print oTbl.Cell(1, 1).Range.ParagraphFormat.Alignment
Set oRng = oTbl.Cell(1, 1).Range
Set oTblInsert = oTbl.Tables.Add(oRng, 1, 1)
With oTblInsert
.PreferredWidthType = wdPreferredWidthPoints
.PreferredWidth = 25
.Cell(1, 1).Range.Text = "C"
End With
'Alignment - Returns 1 (Center aligned), but the content is visibly left aligned!!
Debug.Print oTbl.Cell(1, 1).Range.ParagraphFormat.Alignment
Set oRng = oTbl.Cell(1, 1).Range
oRng.Select
'Now look Home>Paragraph group. Center alinged is selected for the selection, but the cell content is
'clearly not centered in the cell!!
'1. With non-printing characters displayed, click outside the table then reselect the
'contents the parent cell (select the C and both end of cell markers displayed)
'2. Now Home>Paragraph displays the visible alignment (Left).
'3. Click the center alignment control and the parent cell content is center aligned.
'OK good to this point.
'Now it gets really wierd.
'Delete the table and run this procedure again.
'This time:
'1. Repeat steps 2 and 3 above.
'2. Notice that Home>Paragraph clearly shows the content is "Left" aligned as it physically is!!
'3. Start the Macro recorder
'4. Click the Home tab to apply paragraph center alignment.
'5. Curses!!!! The Home>Paragraph group indicates that center alignment is already applied!!
End Sub


What am I doing wrong or not doing?

Thanks

macropod
12-24-2012, 12:30 AM
Hi Greg,

It appears that, when inserting a nested table, the cell alignment of the parent cell reverts to the default (left, in this case). Try:
With oTblInsert
.Rows.Alignment = wdAlignRowCenter
Note that, although the nested table will now be centred in the parent cell, the parent cell's alignment will still be 'left' and you cannot now change it to centred.

gmaxey
12-24-2012, 05:59 AM
Paul,
Right. Thanks. Odd behaviour isn't it!