Word vba - How to tell if text will fit on a page?

User avatar
kdock
5StarLounger
Posts: 720
Joined: 21 Aug 2011, 21:01
Location: The beautiful hills of Western North Carolina

Word vba - How to tell if text will fit on a page?

Post by kdock »

I have a macro that inserts blank lines on a page with text ("///") to show that it was intentionally left empty. It works just fine under normal circumstances -- the code just keeps adding the /// down to a certain measurement.

However, if there's a footnote, the macro inserts the /// as if the footnote wasn't there, which has the effect of pushing the /// lines that don't fit because of the footnote to the top of the next page.

I know "page" is a slippery concept with Word. But is there a way of detecting whether a footnote is on a page, how much room it will take up and inserting only enough ///s to fit between the last line of real text and the top of the footnote?

Thanks! Kim
"Hmm. What does this button do?" Said everyone before being ejected from a car, blown up, or deleting all the data from the mainframe.

User avatar
HansV
Administrator
Posts: 78549
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Word vba - How to tell if text will fit on a page?

Post by HansV »

The following might be slow. It checks each time we add a paragraph whether its position is lower down than the previous one, and stops when the position is higher (indicating that we moved to the next page).
The code assumes that you have already moved the insertion point to the "blank" page.

Code: Select all

    Dim dblTop As Double
    Dim dblPrevTop As Double
    Do
        Selection.TypeText "///"
        ' Get current position
        dblPrevTop = Selection.Information(wdVerticalPositionRelativeToPage)
        ' Insert paragraph mark
        Selection.TypeParagraph
        ' Get new position
        dblTop = Selection.Information(wdVerticalPositionRelativeToPage)
    Loop Until dblTop < dblPrevTop
    ' Remove last paragraph mark
    Selection.TypeBackspace
Best wishes,
Hans

User avatar
kdock
5StarLounger
Posts: 720
Joined: 21 Aug 2011, 21:01
Location: The beautiful hills of Western North Carolina

Re: Word vba - How to tell if text will fit on a page?

Post by kdock »

Hans: Yes! Thank you!

It's not slow, especially since this is done on a page-by-page, as-needed basis. The only addition I made was that the /// has its own style, so I added that above the Do line.

It's perfect. :fanfare: :thankyou: :clapping:

Kim
"Hmm. What does this button do?" Said everyone before being ejected from a car, blown up, or deleting all the data from the mainframe.