从Excel VBA向新创建的Word文档插入页眉/页脚

3

我正在尝试从Excel中的内容创建Word文档。当我尝试在Word中添加页眉/页脚时,我遇到了错误“运行时错误5941:集合的请求成员不存在”,这个错误出现在以下代码行.Headers(wdHeaderFooterPrimary).Range.Text = "Header 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个回答

3

我认为您不能使用.Range.Text
相反,尝试将引用分配给一个范围对象。要使其工作,您需要在引用中添加“Microsoft Word XX.X Object Library”。

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

我尝试过这个,Dim objRange as Word.Range 显示了“用户定义类型未定义”的错误。在引用中,我确实有Microsoft Office Library。而且我尝试使用Range类型代替Word.Range,但是当我在 Set objRange = .Headers(wdHeaderFooterIndex.wdHeaderFooterPrimary).Range 这一行时,它显示了“运行时错误242:对象所需”。 - user2048724
你需要在引用中添加Microsoft Word对象库。 - Niclas
我从引用中添加了这个库,它完美地工作了。谢谢 Niclas。 - user2048724
我更新了代码,包括页脚 :-) - Niclas
@user2048724 如果这个方案对您有用,请接受它作为答案。谢谢。 - Niclas
选择作为答案。再次感谢! - user2048724

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接