当单词未打开时,从Excel中的模板创建Word文档

时间:2014-05-20 21:49:09

标签: excel vba ms-word word-vba

我有一个excel文件生成一些图形,我正在尝试在Word中创建一个报告来提取这些图形。我已经设置好了所有工作,但除非Word已经打开,否则不会生成Word文件。这是我到目前为止的一小部分 - 我错过了什么?

Sub Generate_Report()
Dim wordApp As Object
Dim templateFile As Object
On Error Resume Next

' Define template word file
Set wordApp = GetObject(, "Word.Application") 'gives error 429 if Word is not open
If Err = 429 Then
    Set wordApp = CreateObject("Word.Application") 'creates a Word application
    ' wordapp.Documents.Open ThisWorkbook.Path & "\WeatherShift_Report_Template.docm"
    wordApp.Visible = True
    Err.Clear
End If

Set templateFile = wordApp.Documents.Add(template:=ThisWorkbook.Path & "\WeatherShift_Report_Template.docm")

' Copy charts to new word file
Sheets("Dashboard").Select
ActiveSheet.ChartObjects("Chart 18").Activate
ActiveChart.ChartArea.Copy
With templateFile.Bookmarks
    .Item("dbT_dist_line").Range.Paste
End With

1 个答案:

答案 0 :(得分:4)

您的On Error Resume Next可能会屏蔽以后的错误。

试试这个:

Sub Generate_Report()

    Dim wordApp As Object
    Dim templateFile As Object

    On Error Resume Next
    Set wordApp = GetObject(, "Word.Application") 'gives error 429 if Word is not open
    On Error Goto 0 'stop ignoring errors
    If wordApp Is Nothing Then
        Set wordApp = CreateObject("Word.Application") 'creates a Word application
    End If

    wordApp.Visible = True '<< edit

    Set templateFile = wordApp.Documents.Add(template:=ThisWorkbook.Path _
                                      & "\WeatherShift_Report_Template.docm")

    ' Copy charts to new word file
    Sheets("Dashboard").Select
    ActiveSheet.ChartObjects("Chart 18").Activate
    ActiveChart.ChartArea.Copy
    With templateFile.Bookmarks
        .Item("dbT_dist_line").Range.Paste
    End With
End Sub