简体   繁体   中英

VBA (Word) How to insert a Page Break at Paragraph?

I am trying to insert a page break at a specific paragraph, but it always inserts the page break at the first line/paragraph of the document, I don't understand why. Any ideas?

With Word.ActiveDocument
    .Paragraphs(15).Range.Collapse Direction:=wdCollapseEnd
    .Paragraphs(15).Range.InsertBreak WdBreakType.wdPageBreak
    'or this way (Is there a differece): .Paragraphs(15).Range.InsertBreak Type:=wdPageBreak
End With

Thanks Julius

I see something different: for me, it replaces the specified paragraph with the page break, as described in the Help topic.

In any case, the key to this is to work with a specific Range object. It's not possible to "collapse" the entire 15th paragraph - the method has no action. The paragraph Range needs to be assigned to an independent Range object, which can be collapsed, then the page break inserted at that Range object.

For example:

Sub TestInsertPageBreak()
    Dim paraRange As Word.Range

    With ActiveDocument
        Set paraRange = .Paragraphs(15).Range
        paraRange.Collapse Direction:=wdCollapseEnd
        paraRange.InsertBreak WdBreakType.wdPageBreak
    End With
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM