Friday, April 9, 2010

Split a word document into separate files

Here is a macro that can automatically split a large word document into several small ones.

1. Open you word file
2. Go to the View Tab > Macros > View Macro (or press ALT + F8)
3. In the Macro name box, type split
4. Click Create to open the Visual Basic Editor
5. Overwrite the newly created split subroutine with the code below
6. Create a tmp directory in drive c:
7. Run this macro

Sub split()
'
' split Macro
'
'
' Used to set criteria for moving through the document by page.
   Application.Browser.Target = wdBrowsePage

   For i = 1 To ActiveDocument.BuiltInDocumentProperties("Number of Pages")
     
      'Select and copy the text to the clipboard
      ActiveDocument.Bookmarks("\page").Range.Copy

      ' Open new document to paste the content of the clipboard into.
      Documents.Add
      Selection.Paste
' Removes the break that is copied at the end of the page, if any.
      Selection.TypeBackspace
      ChangeFileOpenDirectory "C:\tmp"
      DocNum = DocNum + 1
      ActiveDocument.SaveAs FileName:="Page_" & DocNum & ".doc"
      ActiveDocument.Close

      ' Move the selection to the next page  in the document
      Application.Browser.Next
   Next i
   ActiveDocument.Close savechanges:=wdDoNotSaveChanges

End Sub