使用 VBA,如何在 Excel 中的 Word 中编写不同标题级别的文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12832289/
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 VBA, how can I write text of different heading levels in Word from Excel?
提问by chemicalkt
Using VBA 2007, how can I create a Word document from Excel and write text of different headings (heading1, heading2, normal) so that the headings would appear in the document map?
使用 VBA 2007,如何从 Excel 创建 Word 文档并编写不同标题(heading1、heading2、normal)的文本,以便标题出现在文档映射中?
回答by CuberChase
This example will run from Excel. It uses Early Binding so you need to ensure you have a reference to Word set in the VBA References (Tools->References).
此示例将从 Excel 运行。它使用早期绑定,因此您需要确保在 VBA 引用(工具->引用)中设置了对 Word 的引用。
Word can be a fickle best with putting text in the document. Generallyit needs to go a the currently selected point. You can use Bookmarks and/or field codes to put text in different locations within a document.
在文档中放置文本时,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