使用 VBA 2007,如何从 Excel 创建 Word 文档并编写不同标题(标题 1、标题 2、普通)的文本,以便标题出现在文档映射中?
问问题
13413 次
1 回答
4
此示例将从 Excel 运行。它使用早期绑定,因此您需要确保在 VBA 参考(工具->参考)中设置了对 Word 的参考。
将文本放入文档中,Word 可能是一个善变的最佳选择。 一般它需要去一个当前选择的点。您可以使用书签和/或域代码将文本放置在文档中的不同位置。
Sub MakeWordDocumentWithHeadings()
Dim wdApp As Word.Application, wdDoc As Word.Document
'Use on error resume next so VBA doesn't produce an error if it can't find Word Open
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
'If it is nothing the open a new instance of word
If wdApp Is Nothing Then Set wdApp = New Word.Application
'Reset the errors
On Error GoTo 0
'Add a new document
Set wdDoc = wdApp.Documents.Add
'Word works by the location of the 'selection'
wdApp.Selection.Style = ActiveDocument.Styles("Heading 1")
wdApp.Selection.TypeText Text:="Heading One"
wdApp.Selection.TypeParagraph
wdApp.Selection.Style = ActiveDocument.Styles("Heading 2")
wdApp.Selection.TypeText Text:="Heading Two"
wdApp.Selection.TypeParagraph
wdApp.Selection.Style = ActiveDocument.Styles("Heading 3")
wdApp.Selection.TypeText Text:="Heading Three"
wdApp.Selection.TypeParagraph
'Save close or whatever here
'Always set objects to nothing.
Set wdDoc = Nothing
Set wdApp = Nothing
End Sub
于 2012-10-11T10:02:44.680 回答