这是我第一次编写VBA。我需要使用数据库中的数据生成Word Doc(仅限Selected Tables)。我设法使用XXX.Selection.TypeText
在文档中创建了包含一些文本的Word文档。但是,我无法弄清楚如何在报告中包含页眉和页脚。我尝试了很多方法,但我无法得到我想要的结果。
我的问题是,我可以使用/打开一个预定义的word文档(带有Headers和Foots)并在预定义的word文档中填充我的数据?
谢谢!
答案 0 :(得分:4)
查看以下代码:
这将创建一个新的word文档,包括页眉和页脚内容以及正文内容。
注意:不要忘记添加Microsoft Word对象的引用
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