使用 MS Access 和 VBA 生成 Ms Word 文档
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24031426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using MS Access and VBA to generate Ms Word Document
提问by Alfred
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.
这是我第一次编写 VBA。我需要使用我的数据库中的数据生成一个 Word Doc(仅限选定表)。我设法使用XXX.Selection.TypeText
. 但是我不知道如何为报告包含页眉和页脚。我尝试了很多方法,但无法得到我想要的结果。
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?
我的问题是,我可以使用/打开预定义的 Word 文档(带有页眉和页脚)并在该预定义的 Word 文档中填充我的数据吗?
Thank you!
谢谢!
回答by Access Guru
Have a look on the following code:
看看下面的代码:
this will create a new word document including header and footer content as well as body content.
这将创建一个新的 Word 文档,包括页眉和页脚内容以及正文内容。
NOTE:Don't forget to add reference for Microsoft Word Object
注意:不要忘记为 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