shipr
shipr

Reputation: 2839

VBA for Word - position text boxes based on page

After adding a large number (150?) of callouts (simple text boxes in the margin, with no borders) to a Word 2010 .docx file with mirrored odd/even pages, I needed to adjust some text. This shortened the document enough to remove a page, and therefore all the odd pages following the adjustment became even, and the even became odd. The text boxes did not move, and now they all fall off the edge of the paper, where it is difficult even to find them all due to the text outside the bounds of the paper not being shown in the document, let alone to move them to their correct positions in the opposite margin. Moreover, I may need to adjust text again and the problem could recur.

I'm looking for an automated way, using VBA (in which I am decidedly a rank novice, though an expert programmer), to record some macro to say, "Center all existing text boxes in the wide margin, and make the width consistent." Something like,

As a text box, if I find myself on an odd page, make the left edge of the text box 0.5" from the left edge of the page; if I am found on an even page, make the left edge of the text box at the right margin + 0.5". My height should be consistent, and my height can stay what it was already.

I need to know in what units to express the Top and Width values, how to determine if I am on an odd/even page, and how to find all the text boxes.

Can anyone help?

Upvotes: 0

Views: 5919

Answers (1)

joeschwa
joeschwa

Reputation: 3175

Sub AdjustTextBoxes()

Dim myTextBox As Shape
Dim PageNumber As Integer

For Each myTextBox In ActiveDocument.Shapes
    If myTextBox.Type = msoTextBox Then
        myTextBox.Select
        PageNumber = Selection.Information(wdActiveEndPageNumber)
        'Mod returns the remainder (rounded up) of the division.
        'No remainder is even. Any remainder is an odd page.
        If PageNumber Mod 2 = 1 Then
            With myTextBox 'Odd numbered pages
                .RelativeHorizontalPosition = wdRelativeHorizontalPositionPage 
                .Left = InchesToPoints(0.5)
            End With
        Else
            'Because wdRelativeHorizontalPositonPage measures from the left
            'edge of the page the positioning for text boxes on even pages
            'is not based on the distance from the right margin.
            'So below .Left = 8.5" (page width) - (1" (textbox with) + .5" (distance
            'from the right edge of the page). The measurement for .left below
            'will need to be altered based on the position from the right edge
            'of the page and the width of your text boxes and pages.
            With myTextBox 'Even numbered pages
                .RelativeHorizontalPosition = wdRelativeHorizontalPositionPage
                .Left = InchesToPoints(7)
            End With
        End If
    End If
Next

End Sub

Upvotes: 1

Related Questions