使用VBA,如何从Excel中编写Word中不同标题级别的文本?

时间:2012-10-11 04:36:29

标签: excel vba excel-vba

使用VBA 2007,如何从Excel创建Word文档并编写不同标题的文本(heading1,heading2,normal),以便标题显示在文档结构图中?

1 个答案:

答案 0 :(得分:2)

此示例将从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