vbams-wordnested-table

How to determine the cell size of a nested table cell in VBA for Microsoft Word?


It seems that VBA retrieves a false value for the cell height of a nested table cell. The primary table

After selecting a form field, I try to get position and size (x1,y1,x2,y2) with the following code:

ActiveDocument.Fields(xx).Select  ' Fields(xx) element is inside a cell of a nested table
x1 = Selection.Information(wdHorizontalPositionRelativeToPage) - (Selection.Cells.Width / 2)
x2 = Selection.Information(wdHorizontalPositionRelativeToPage) + (Selection.Cells.Width / 2)
y1 = Selection.Information(wdVerticalPositionRelativeToPage) + (Selection.Cells.Height / 2) + (Selection.font.SIZE / 2)
y2 = Selection.Information(wdVerticalPositionRelativeToPage) - (Selection.Cells.Height / 2) + (Selection.font.SIZE / 2)

With a regular table Selection.Cells.Height returns the correct value. With a nested table Selection.Cells.Height returns 9999999 instead of the real value.

Is there a workaround to determine the cell height?


Solution

  • Height property returns 9999999 because the HeightRule default to the WdRowHeightRule.wdRowHeightAuto(ie. = 0). It doesn't matter if it's a nested table or not. So if you want to get the exact value of the Height property, You first should set the value of HeightRule to not wdRowHeightAuto( wdRowHeightAtLeast =1 or wdRowHeightExactly =2) before reading this property.

    Suppose your Height is set to 0.42 cm, then your code should be like this:

    Sub t()
        Dim x1, x2, y1, y2
        ActiveDocument.Fields(xx).Select  ' Fields(xx) element is inside a cell of a nested table
        With Selection.Cells
            .HeightRule = wdRowHeightAtLeast
            '.Height = CentimetersToPoints(0.42)
        End With
        x1 = Selection.Information(wdHorizontalPositionRelativeToPage) - (Selection.Cells.Width / 2)
        x2 = Selection.Information(wdHorizontalPositionRelativeToPage) + (Selection.Cells.Width / 2)
        y1 = Selection.Information(wdVerticalPositionRelativeToPage) + (Selection.Cells.Height / 2) + (Selection.Font.Size / 2)
        y2 = Selection.Information(wdVerticalPositionRelativeToPage) - (Selection.Cells.Height / 2) + (Selection.Font.Size / 2)
    End Sub