Reputation: 59
this is the first time I coding VBA. I need to generate a Word Doc using the data in my database (Selected Tables Only). I managed to create the Word Doc with some text inside the document using XXX.Selection.TypeText
. However I can't figure out how to include the Header and Footer for the report. I tried many ways and I can't get the results i wanted.
My question is, it is possible for me to use/open a prefined word document (with Headers and Foots) and populated my data inside that prefined word document?
Thank you!
Upvotes: 4
Views: 33252
Reputation: 193
Have a look on the following code:
this will create a new word document including header and footer content as well as body content.
NOTE: Don't forget to add reference for Microsoft Word Object
Dim objWord As Word.Application
Dim doc As Word.Document
Dim WordHeaderFooter As HeaderFooter
Set objWord = CreateObject("Word.Application")
With objWord
.Visible = True
Set doc = .Documents.Add
doc.SaveAs CurrentProject.Path & "\TestDoc.doc"
End With
With objWord.Selection
.Font.Name = "Trebuchet MS"
.Font.Size = 16
.TypeText "Here is an example test line, #" & " - Font size is " & .Font.Size
.TypeParagraph
'Add header and footer
ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range.Text = "Header"
ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).Range.Text = "Footer"
End With
doc.Save
doc.Activate
Upvotes: 8