gpt4 book ai didi

excel - 当 Word 未打开时,从 Excel 模板创建 Word 文档

转载 作者:行者123 更新时间:2023-12-03 02:04:42 32 4
gpt4 key购买 nike

我有一个生成一些图形的 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

最佳答案

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

关于excel - 当 Word 未打开时,从 Excel 模板创建 Word 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23770568/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com