1
votes

I've combined 3000 documents into one word file which are all separated by a section break. Is there a Macro that would automatically number each document along the lines of 0001, 0002 etc.?

1

1 Answers

1
votes

Yes, here is the code that:

  • finds section break (^b)
  • changes it for manual page break (^m) and the number of it.

Further information, about finding wildcards, special characters etc in Word (like ^b - section break; ^m - manual break): Find and replace text or other items (support.office.com)

Here is the code:

Option Explicit
Sub changeSectionsForPageBreaksAndNumbers()
    Dim i, countSections, sectionNumber
    countSections = ActiveDocument.Sections.Count

    'Loop that changes section breaks for page break + # + number of the section (from 2 to last section)
    For i = 1 To countSections Step 1
        sectionNumber = i + 1
        Selection.Find.ClearFormatting
        Selection.Find.Replacement.ClearFormatting
        With Selection.Find
            .Text = "^b"
            .Replacement.Text = "^m" & "#" & Right("0000" & sectionNumber, 4) & vbCr
            .Forward = True
            .Wrap = wdFindStop
            .Format = False
            .MatchCase = True
            .MatchWholeWord = False
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
        End With
        Selection.Find.Execute Replace:=wdReplaceOne
        Selection.MoveRight Unit:=wdCharacter, Count:=1
    Next

    'first number in the beginning of the document
    Selection.HomeKey Unit:=wdStory
    Selection.InsertBefore "#0001" & vbCr

    MsgBox ("Total sections: " & countSections)
End Sub
  • vbCr — new line
  • "#" & Right("0000" & "1", 4) — results in #0001. This part pushes "1" to the right of this string, but limits it to 4 digits.