Search code examples
vbareplacems-wordpage-break

Looping through a Word Document and Replacing a String with PageBreak


I want to replace every occurrence of the string "#PAGEBREAK# with an actual pagebreak. This is what I came up with:

Sub InsertPageBreak()

    Application.ScreenUpdating = False
    With ActiveDocument.Range
        With .Find
            .ClearFormatting
            .Replacement.ClearFormatting
            .Text = "#PAGEBREAK#"
            .Replacement.Text = ""
            .Forward = True
            .Wrap = wdFindContinue
            .Format = True
            .InsertBreak Type:=wdPageBreak
            .Execute
        End With
    End With
    Application.ScreenUpdating = True

End Sub

What actually happens: The string "#PAGEBREAK#" is exchanged for an empty string. The .Find works as intended but I get the error message:

Method or Object not found

on the

.InsertBreak Type:= wdPageBreak

What methods could be used here in which way?


Solution

  • This will work For you:

    Sub InsertPageBreak()
    
    
        ActiveDocument.Range.Select
    
            With Selection.Find
                    .Text = "#PAGEBREAK#"
                    .Execute
            End With
    
            If Selection.Find.Found Then
    
                Selection.GoTo What:=wdGoToBookmark, Name:="\Page"
                Selection.MoveRight Unit:=wdCharacter, Count:=1
                Selection.MoveLeft Unit:=wdCharacter, Count:=1
                Selection.InsertBreak Type:=wdPageBreak
    
            End If
    End Sub
    

    If you want to Replace all of the "#PAGEBREAK#", use this below code:

    Sub InsertPageBreak()
    
    
       ActiveDocument.Range.Select
    
        Do
    
        With Selection.Find
                .Text = "#PAGEBREAK#"
                .Execute
        End With
    
            If Selection.Find.Found Then
    
                Selection.GoTo What:=wdGoToBookmark, Name:="\Page"
                Selection.MoveRight Unit:=wdCharacter, Count:=1
                Selection.MoveLeft Unit:=wdCharacter, Count:=1
                Selection.InsertBreak Type:=wdPageBreak
    
            Else: Exit Sub
    
            End If
        Loop
    
    
    End Sub