Cabrill
01-22-2014, 04:30 PM
Hello, and thank you for taking the time to read this post. I'm trying to use VBA in Word 2010 to split up a document with both section breaks and page breaks scattered at unpredictable points. How can I easily grab each group of sections between page breaks to copy into new documents? This is the code I've been working with:
Private Sub BreakOnPageBreak(myDoc As Document)
Dim MyNumPages As Integer
Dim newDoc As Document
Dim mySection As Section
MyNumPages = 0
For Each mySection In ActiveDocument.Sections
MyNumPages = MyNumPages + 1
mySection.Range.Copy
Set newDoc = Documents.Add
Selection.Collapse Direction:=wdCollapseStart
newDoc.Range.PasteAndFormat (wdFormatOriginalFormatting)
newDoc.SaveAs FileName:=SourceName & "_" & MyNumPages & ".doc", _
AddToRecentFiles:=False
newDoc.Close
Next mySection
myDoc.Close SaveChanges:=wdDoNotSaveChanges
End Sub
The problem, as you may have guessed, is that it copies each individual section to a new document and not the whole sections that exist between page breaks. I've tried experiementing with
If mySection.Range.PageSetup.SectionStart = wdSectionNewPage
pageRange.Start = mySection.Range.Start
ElseIf ...?
However, I couldn't figure out a method to determine if the section I'm looking at is the LAST section before a page break so I could set the end of my pageRange before copying. Would anyone be so kind as to help me iterate through the content between page breaks to copy it out? Thank you in advance ever so much for your appreciated assistance!
Private Sub BreakOnPageBreak(myDoc As Document)
Dim MyNumPages As Integer
Dim newDoc As Document
Dim mySection As Section
MyNumPages = 0
For Each mySection In ActiveDocument.Sections
MyNumPages = MyNumPages + 1
mySection.Range.Copy
Set newDoc = Documents.Add
Selection.Collapse Direction:=wdCollapseStart
newDoc.Range.PasteAndFormat (wdFormatOriginalFormatting)
newDoc.SaveAs FileName:=SourceName & "_" & MyNumPages & ".doc", _
AddToRecentFiles:=False
newDoc.Close
Next mySection
myDoc.Close SaveChanges:=wdDoNotSaveChanges
End Sub
The problem, as you may have guessed, is that it copies each individual section to a new document and not the whole sections that exist between page breaks. I've tried experiementing with
If mySection.Range.PageSetup.SectionStart = wdSectionNewPage
pageRange.Start = mySection.Range.Start
ElseIf ...?
However, I couldn't figure out a method to determine if the section I'm looking at is the LAST section before a page break so I could set the end of my pageRange before copying. Would anyone be so kind as to help me iterate through the content between page breaks to copy it out? Thank you in advance ever so much for your appreciated assistance!