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

标签 excel vba ms-word

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

相关文章:

excel - 如何创建 "if x ≥ then multiply by y"等的公式?

vba - 更改用户窗体中的选项按钮选择

c# - STA 中的 Akka.net 参与者

ms-word - 转换 MS Word "curly"引号和撇号

ms-word - x64 Word 2010 使用 WiX 加载项注册

vba - 如何解决错误的 "spreadsheet locked for editing"问题?

sql - MS Access 2010 SQL 选择计算列问题

excel - 如果范围没有填充颜色,则显示错误

vba - 需要更好的优化代码吗?

vba - 如何使用 Selenium 和 VBA 设置 Chrome 下载目录