Word

Separate a Document by Headings

Ease of Use

Easy

Version tested with

2002 

Submitted by:

Jacob Hilderbrand

Description:

This macro will seperate a document into seperate documents for each Heading 1 in the original document. 

Discussion:

You have a document with several sections setup as a Heading 1. You want to seperate all those into seperate documents, but you don't want to cut and paste it all manually. This macro will do all the work for you. All the seperate documents are automatically saved and closed. They will be in the same folder as the original document. 

Code:

instructions for use

			

Option Explicit Sub SeperateHeadings() Dim TotalLines As Long Dim x As Long Dim Groups() As Long Dim Counter As Long Dim y As Long Dim FilePath As String Dim FileName() As String FilePath = ActiveDocument.Path Selection.GoTo What:=wdGoToLine, Which:=wdGoToAbsolute, Count:=1 Do TotalLines = Selection.Range.Information(wdFirstCharacterLineNumber) Selection.MoveDown Unit:=wdLine, Count:=1 Loop While TotalLines <> Selection.Range.Information(wdFirstCharacterLineNumber) Selection.GoTo What:=wdGoToLine, Which:=wdGoToAbsolute, Count:=1 For x = 1 To TotalLines If Selection.Style = "Heading 1" Then Counter = Counter + 1 ReDim Preserve Groups(1 To Counter) ReDim Preserve FileName(1 To Counter) Groups(Counter) = x Selection.EndKey Unit:=wdLine, Extend:=wdExtend FileName(Counter) = Selection.Text FileName(Counter) = Left(Selection.Text, Len(FileName(Counter)) - 1) Selection.HomeKey Unit:=wdLine, Extend:=wdExtend End If Selection.MoveDown Unit:=wdLine, Count:=1 Next Counter = Counter + 1 ReDim Preserve Groups(1 To Counter) Groups(Counter) = TotalLines For x = 1 To UBound(Groups) - 1 y = Groups(x + 1) - Groups(x) Selection.GoTo What:=wdGoToLine, Which:=wdGoToAbsolute, Count:=Groups(x) Selection.MoveDown Unit:=wdLine, Count:=y, Extend:=wdExtend Selection.Copy Documents.Add Selection.Paste ActiveDocument.SaveAs FilePath & "\" & FileName(x) & ".doc" ActiveDocument.Close Next x End Sub

How to use:

  1. Open Word.
  2. Alt + F11 to open the VBE.
  3. Insert | Module.
  4. Paste the code in the Module Code Window.
  5. Close the VBE (Alt + Q or press the X in the top-right corner).
 

Test the code:

  1. Add text to a document and setup some sections with "Heading 1" style.
  2. Tools | Macro | Macros.
  3. Select SeperateHeadings and press Run.
 

Sample File:

Text Split.ZIP 9.53KB 

Approved by mdmackillop


This entry has been viewed 247 times.

Please read our Legal Information and Privacy Policy
Copyright @2004 - 2020 VBA Express