Word – How to replace all breaks in a selection in Word using VBA

microsoft wordvba

I've got a part of a document selected, and now I want to replace all manual page and section breaks (the latter of all types, such as next page even, next page uneven, next page, continuous, column) within that selection.

I tried to record a macro while using words advanced find/replace searching for [^m^b], but that did not work (found nothing in a document that I'd spammed with the breaks for testing).

So I tried to handle section and page breaks separately, first selecting, then replacing one type, selecting again, replacing the other type. This way, the second search (for section breaks) for some reason also touched a part of the document before the selection.

However, how do I search for the special section breaks? The advanced find UI has no option to search specifically for them, but the regular section break search does not find everything. Also, I assume there is a way to do all in one go.

An update, I'm now trying the section breaks separately. The macro below does replace all section breaks, but does something weird and wrong. I've got four section breaks, all of type continuous before the selection, then one section break of type next page and one section break of type even page in the selection. After running a macro for replacing section breaks the last section break before the selection changes from type continuous to type even page.

My macro:

Sub break2()
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
    .Text = "^b"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = False
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchKashida = False
    .MatchDiacritics = False
    .MatchAlefHamza = False
    .MatchControl = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub

Best Answer

This simple code removes all breaks. Only one remains, which is not common - "Text Wrap Break". If you want that to be also removed, just add "^l" in the Array() parameters. But have in mind that "^l" will also match "Line Break". Anyway, you did not mention Text Wrap Breaks, and it is not that common, so I think that's not a problem. Hope that will help someone ;)

Sub Delete_all_breaks_from_selection()
Dim arr() As Variant
Dim i As Byte

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
'"^b" - Selection Breaks, "^m" - Page Break, "^n" - Column Break
arr = Array("^b", "^m", "^n")
    For i = LBound(arr) To UBound(arr)
        With Selection.Find
            .Text = arr(i)
            .Replacement.Text = ""
        End With
    Selection.Find.Execute Replace:=wdReplaceAll
    Next
End Sub
Related Question