将页眉/页脚插入Excel VBA中新创建的Word文档

时间:2016-11-03 14:19:20

标签: excel vba excel-vba word-vba

我试图从Excel中的内容创建word文档。 当我尝试在单词中添加页眉/页脚时,我收到错误"运行时错误5941:所请求的集合成员不存在"在线.Headers(wdHeaderFooterPrimary).Range.Text ="标题文字"。请建议我如何使用它?

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:\Users\2021282\Desktop\FAQ"
End Sub

1 个答案:

答案 0 :(得分:2)

我认为你不能使用.Range.Text
而是尝试为范围对象分配引用。要完成这项工作,您需要添加&#34; Microsoft Word XX.X对象库&#34;在参考文献中。

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