Home » excel » Using VBA, how can I write text of different heading levels in Word from Excel?

Using VBA, how can I write text of different heading levels in Word from Excel?

Posted by: admin May 14, 2020 Leave a comment

Questions:

Using VBA 2007, how can I create a Word document from Excel and write text of different headings (heading1, heading2, normal) so that the headings would appear in the document map?

How to&Answers:

This example will run from Excel. It uses Early Binding so you need to ensure you have a reference to Word set in the VBA References (Tools->References).

Word can be a fickle best with putting text in the document. Generally it needs to go a the currently selected point. You can use Bookmarks and/or field codes to put text in different locations within a document.

Sub MakeWordDocumentWithHeadings()

    Dim wdApp As Word.Application, wdDoc As Word.Document

    'Use on error resume next so VBA doesn't produce an error if it can't find Word Open
    On Error Resume Next
    Set wdApp = GetObject(, "Word.Application")

    'If it is nothing the open a new instance of word
    If wdApp Is Nothing Then Set wdApp = New Word.Application
    'Reset the errors
    On Error GoTo 0

    'Add a new document    
    Set wdDoc = wdApp.Documents.Add

    'Word works by the location of the 'selection'
    wdApp.Selection.Style = ActiveDocument.Styles("Heading 1")
    wdApp.Selection.TypeText Text:="Heading One"
    wdApp.Selection.TypeParagraph
    wdApp.Selection.Style = ActiveDocument.Styles("Heading 2")
    wdApp.Selection.TypeText Text:="Heading Two"
    wdApp.Selection.TypeParagraph
    wdApp.Selection.Style = ActiveDocument.Styles("Heading 3")
    wdApp.Selection.TypeText Text:="Heading Three"
    wdApp.Selection.TypeParagraph

    'Save close or whatever here

    'Always set objects to nothing.  
    Set wdDoc = Nothing
    Set wdApp = Nothing

End Sub