1
我試圖從Excel中的內容創建word文檔。 當我嘗試在單詞中添加頁眉/頁腳時,出現錯誤「運行時錯誤5941:集合的請求成員不存在」.Headers(wdHeaderFooterPrimary).Range.Text =「Header text」 。請建議我如何處理這個問題?從Excel VBA中插入頁眉/頁腳到新創建的Word文檔中
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
我試過這個和'Dim objRange as Word.Range'顯示_user定義的類型not defined_ error。在參考資料中,我確實有Microsoft Office Library。而不是使用Word.Range我試着Range類型,然後它顯示錯誤上設置objRange = .Headers(wdHeaderFooterIndex.wdHeaderFooterPrimary).Range'作爲_Run時間錯誤242:對象Required_ – user2048724
您需要參考 – Niclas
下的Microsoft Word對象庫只要用你的代碼測試過,它應該可以工作。 – Niclas