[英]Create word document from template from Excel when word isn't open
I have an excel file that generates some graphics, and I am trying to create a report in Word that pulls some of these graphics. 我有一个生成一些图形的Excel文件,并且我试图在Word中创建一个提取其中一些图形的报告。 I have everything set up and working, but the Word file isn't generated unless Word is already open. 我已经完成所有设置并可以正常工作,但是除非Word已打开,否则不会生成Word文件。 This is a snippet of what I have so far - what am I missing? 这是我到目前为止的摘要-我想念的是什么?
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
Your On Error Resume Next
may be masking a later error. 您的On Error Resume Next
可能掩盖了以后的错误。
Try this: 尝试这个:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.