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

我有一个生成一些graphics的Excel文件,我试图在Word中创build一个报告,这些graphics拉一些。 我有一切设置和工作,但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 

您的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