Home » excel » Inserting Header/Footer into newly created word document from Excel VBA

Inserting Header/Footer into newly created word document from Excel VBA

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m trying to create word document from content in Excel.
When I tryto add header/footer in the word, I’m getting an error “Run Time Error 5941 : The requested member of the collection does not exist” on line .Headers(wdHeaderFooterPrimary).Range.Text = “Header text”. Please suggest how I can work with this?

Sub CreateFAQWord()
Dim myRow As Long
Dim objWord As Object
Dim objDoc As Object
Dim question As String
Dim answer As String
Dim rng As Range
Dim i As Long

Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set objDoc = objWord.Documents.Add()

objWord.Selection.Style = objDoc.Styles("Title")
objWord.Selection.Paragraphs.Alignment = 1
objWord.Selection.TypeText Text:="Title"
objWord.Selection.TypeParagraph
objWord.Selection.TypeParagraph

With objDoc
    .Styles.Add ("BoldNormal")
        With .Styles("BoldNormal").Font
            .Name = "Calibri"
            .Size = 11
            .Bold = True
            .Italic = True
            .Underline = False
        End With
End With
myRow = 2
' Value 2 here is the column in which questions are present. Change accordingly
While Cells(myRow, 2).Value <> ""
    ' Value 9 here is the column in which Yes/No is present. Change accordingly
    If Cells(myRow, 9) = "Yes" Then
        objDoc.Activate
        question = Cells(myRow, 2)
        answer = Cells(myRow, 3)
        objWord.Selection.Style = objDoc.Styles("BoldNormal")
        objWord.Selection.TypeText Text:=question
        objWord.Selection.TypeParagraph
        objWord.Selection.Style = objDoc.Styles("Normal")
        objWord.Selection.TypeText Text:=answer
        objWord.Selection.TypeParagraph
        objWord.Selection.TypeParagraph
    End If
    myRow = myRow + 1
Wend

For i = 1 To objDoc.Sections.Count
   With objDoc.Sections(i)
       .Headers(wdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Text = "Header text"
       .Footers(wdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Text = "Footer text"
   End With
Next

' Change the location path of where you want the document to be saved as needed
objDoc.SaveAs "C:\Users21282\Desktop\FAQ"
End Sub
How to&Answers:

I do not think you can use .Range.Text
Instead try to assign a reference to a range object. To make this work you need to add the “Microsoft Word XX.X Object Library” under references.

Dim objRange as Word.Range

For i = 1 To objDoc.Sections.Count
With objDoc.Sections(i)

    Set objRange = .Headers(wdHeaderFooterIndex.wdHeaderFooterPrimary).Range
    objRange = "Header Text"
    Set objRange = Nothing

    Set objRange = .Footers(wdHeaderFooterIndex.wdHeaderFooterPrimary).Range
    objRange = "Footer text"
    Set objRange = Nothing
End With
Next