Search code examples
vbams-wordpositionbounding-boxparagraph

Find Bounding Box dimensions for a paragraph (Word VBA)


I am using VBA in Word 2016 and I want to create a rectangle the size of the paragraph (I can't use the border feature for other reasons).

I can get the position of the first character using this code, but what about the bottom and right end of the paragraph?

x = Selection.Information(wdHorizontalPositionRelativeToPage)
y = Selection.Information(wdVerticalPositionRelativeToPage)

Unfortunately, the following is just my wishful thinking:

w = Selection.Paragraphs(1).Width 
h = Selection.Paragraphs(1).Height

In the end, I want to execute the following to generate a rectangle the same size as a bounding box around the paragraph:

ActiveDocument.Shapes.AddShape msoShapeRectangle, x, y, w, h

Any help would be appreciated. Thank you!


Solution

  • You are on the right track when you think in terms of the paragraph indicated by your selection. My preference is to deal with the range indicated by the selection, but that is a matter of personal preference. Anyway, the paragraph can be divided into - inter alia - a first character and a last character. As you have already stated, the fist character's position on the page is very near to the top left corner of your rectangle. A similar relationship can be established for the last character. The following code may help you on your way.

    Private Sub TestPos()
    
        Dim Rng As Range
        Dim x As Single, y As Single
    
        Set Rng = Selection.Range
        Set Rng = Rng.Paragraphs(1).Range
        With Rng
            x = .Information(wdHorizontalPositionRelativeToPage)
            y = .Information(wdVerticalPositionRelativeToPage)
            Debug.Print x, y
            .Collapse wdCollapseEnd
            x = .Information(wdHorizontalPositionRelativeToPage)
            y = .Information(wdVerticalPositionRelativeToPage)
            Debug.Print x, y
            Debug.Print .Paragraphs(1).LineSpacing
        End With
    End Sub
    

    As for the left and right you should refer to the margins set for the paragraph. The following code contains the syntax you will need.

    Private Sub ShowPageSetup()
    
        Dim Rng As Range
    
        With ActiveDocument.PageSetup
            Debug.Print .LeftMargin, .RightMargin
        End With
        Set Rng = Selection.Range
        With Rng.Paragraphs(1).Range.ParagraphFormat
            Debug.Print .LeftIndent, .RightIndent
        End With
    End Sub