Microsoft Word Sub Document VBA code example

Microsoft Word Sub Document VBA code example

Subdocument

Sub document can be coming from external file or a range (coming from different section with the same document). Microsoft Word VBA (Visual Basic for Applications) Subdocuments object which exposes all available Subdocuments within a document as collection.

AddFromFile

Following is the file which I saved as “example.docx” and will insert into current document using code:

Note: to perform AddFromFile method the current document must be in Outline Mode as shown below else code will throw error.

  1. Click on View tab
  2. Locate Outline button under Views group as shown below to activate Outline view

Upon activating the Outline View the document view turns as shown below:

Code example

Public Sub InsertSubDocument()
    'Declare document object
    Dim oDocument As Document
    'Bind active document
    Set oDocument = ActiveDocument
    
    'set expanded property to true
    oDocument.Subdocuments.Expanded = True
    
    'Move selectio to the end of the document
    Selection.EndKey Unit:=wdStory
    
    'Insert a new paragraph
    Selection.InsertParagraphBefore
    
    'make sure you are in outline view
    ActiveWindow.ActivePane.View.Type = wdOutlineView
    
    'Insert file
    oDocument.Subdocuments.AddFromFile Name:="C:\Users\nawazish\Downloads\example.docx"
    
    'Memory Cleanup
    Set oDocument = Nothing
End Sub

Output

AddFromRange

We will use same document where we inserted table from “example.docx” file. Now we will use another method which will add selection to end of the document.

Note: AddFromRange needs Heading 1 to be inserted hence we will use code to do the same.

Code example

Public Sub AddFromRangeDocument()
    'Declare document object
    Dim oDocument As Document
    'Bind active document
    Set oDocument = ActiveDocument
    
    'Declare range object
    Dim oRange As Range
    'Bind range object to selection
    Set oRange = Selection.Range
    
    'Make selection to heading 1
    oRange.Style = wdStyleHeading1
    
    'set expanded property to true
    oDocument.Subdocuments.Expanded = True
    
    'Move selectio to the end of the document
    Selection.EndKey Unit:=wdStory
    
    'Insert a new paragraph
    Selection.InsertParagraphBefore
        

    'Insert file
    oDocument.Subdocuments.AddFromRange oRange
    
    'Memory Cleanup
    Set oRange = Nothing
    Set oDocument = Nothing
End Sub

Output

Next >> Microsoft Word Custom Dictionary with code example

Leave a Reply

Your email address will not be published.