View Single Post
 
Old 04-13-2023, 03:24 PM
ctviggen ctviggen is offline Windows 10 Office 2016
Advanced Beginner
 
Join Date: Feb 2021
Posts: 54
ctviggen is on a distinguished road
Default

I just can't figure this out. I have a document that looks like this:


Part 1...
ends with Section Break (Next page)
Part 2...
ends with Section Break (Next page)
Part 3...
document ends


I want to copy all three parts to different documents. Here is test code to copy only the first Part:


Code:
Sub SplitDocumentTest()
    Dim specStart As Range, specEnd As Range
    Dim specDoc As Document
    
    ' Set the section ranges based on the page breaks
    Set specStart = ActiveDocument.Range
    ' Something like this might work to go to a section break, not sure we need the 1....
    Set specEnd = specStart.GoTo(wdGoToSection, wdGoToFirst)
    ' specStart.EndOf Unit:=wdSectionBreakNextPage, Extend:=wdExtend
    ' specStart.EndOf Unit:=wdSection, Extend:=wdExtend
    ' Set specEnd = specStart.GoTo(wdGoToSection, wdGoToNext, 1)
    ' Set specEnd = specStart.GoTo(wdGoToPage, wdGoToAbsolute, 2)
    ' specStart.Select
          
    ' Create new document for this section and copy the content
    Set specDoc = Documents.Add()
    specStart.Copy
    specDoc.Content.Paste
    specDoc.SaveAs2 FileName:="Specification", FileFormat:=wdFormatXMLDocument
    
 End Sub

As you can see, I've tried a ton of stuff, including Gmaxy's recommendation. The entire document, including all three parts, gets copied to the "Specification" document, instead of only Part 1.


What am I doing wrong?
Reply With Quote