Question : Create a new document from sections of a templated document

Hi Guys,

Can anyone show me an example of how I can dynamically create a new MS Word document by programatically (using VBA) grabbing specified sections from a templated document that is split into pre-defined sections. Lets say the template has 10 sections defined. I'd like to be able to create a new document that has section 2, followed by section 6 and section 8.
Is this do-able? If not using sections then I'm open to other suggestions.

Thank you in advance for any contributions

Answer : Create a new document from sections of a templated document

Here is an early binding suggestion
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
Sub BuildDocFromSections()
    Dim wdApp As Word.Application
    Dim docNew As Word.Document
    Dim docSource As Word.Document
    Dim sourcesections As Variant
    Dim i As Integer
    Dim bNewInstance As Boolean
        
    'try to use an existing instance of Word
    On Error Resume Next 'supress error reporting
        Set wdApp = GetObject(, "Word.Application")
    On Error GoTo 0 're-enable error reporting
    
    If wdApp Is Nothing Then
        'Word not running, so create a new instance
        Set wdApp = CreateObject("Word.Application")
        wdApp.Visible = True 'Optional. Code will still work with hidden application
        bNewInstance = True
    End If
    
    
    sourcesections = Array(2, 6, 8)
    Set docSource = wdApp.Documents.Open("C:\MyFolder\MyTemplate.dot")
    Set docNew = wdApp.Documents.Add
    For i = 0 To 2
        docSource.Sections(sourcesections(i)).Range.Copy
        docNew.Bookmarks("\EndOfDoc").Range.Paste
    Next i
    docSource.Close wdDoNotSaveChanges
    
    'Save new document and close application unless it was already running
    docNew.SaveAs "C:\MyFolder\MyNewDoc.dot"
    If bNewInstance Then
        wdApp.Quit
    End If
End Sub
Random Solutions  
 
programming4us programming4us