Skip to content

Instantly share code, notes, and snippets.

@johncblandii
Created October 21, 2016 07:11
Show Gist options
  • Save johncblandii/c0d341fd88cee565c2147a6c52bc26e4 to your computer and use it in GitHub Desktop.
Save johncblandii/c0d341fd88cee565c2147a6c52bc26e4 to your computer and use it in GitHub Desktop.
Microsoft Word macro to merge the current document and split each section into individual files
Sub MergeAndBreakIntoFiles()
'
' Merges the current document and splits each section into individual files
'
'
With ActiveDocument.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
.DataSource.ActiveRecord = wdFirstRecord
.Execute Pause:=False
End With
'A mailmerge document ends with a section break next page.
'Subtracting one from the section count stop error message.
For i = 1 To ((ActiveDocument.Sections.Count) - 1)
'Select and copy the section text to the clipboard
ActiveDocument.Sections(i).Range.Copy
'Create a new document to paste text from clipboard.
With Documents.Add
'Removes the break that is copied at the end of the section, if any.
Selection.MoveUp Unit:=wdLine, Count:=1, Extend:=wdExtend
Selection.Delete Unit:=wdCharacter, Count:=1
Selection.Paste
docName = .Sentences(1) & ".doc"
.SaveAs fileName:=CleanString(docName), AddToRecentFiles:=False
.Close
End With
Next i
ActiveDocument.Close savechanges:=wdDoNotSaveChanges
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment