如何将图表从Excel传输到Word

时间:2016-04-12 17:36:19

标签: excel excel-vba word-vba vba

此函数创建一个单词doc,保存并关闭它,但在我尝试重新打开时失败。它说在远程呼叫时这不起作用。重新开放单词doc的正确做法是什么?或者没有必要再次关闭和打开?看来word和excel之间的沟通很困难。

Sub tester()
    Dim wordApp As Object
    Dim wordDoc As Object
    Dim appendDate As String
    Set wordApp = CreateObject("Word.Application")
    wordApp.Visible = True

    appendDate = "Y"
    fName = "robot"

    If appendDate = "Y" Or appendDate = "y" Then
        fName = ThisWorkbook.Path & "\" & fName & "-" & Format(Now(), "yyyymmdd-hhmm") & ".docx"
    Else
        fName = ThisWorkbook.Path & "\" & fName & ".docx"
    End If

    wordApp.Documents.Add.SaveAs2 fileName:=fName
    wordApp.Documents.Close
    wordApp.Application.Quit
    Set wordDoc = wordApp.Documents.Open(fileName:=fPath, readOnly:=False)
    ThisWorkbook.Sheets("Sheet1").ChartObjects(1).Activate
    ActiveChart.ChartArea.Copy
    wordDoc.Application.Selection.PasteSpecial Link:=False, DataType:=wdPasteOLEObject, Placement:=wdInLine

End Sub

2 个答案:

答案 0 :(得分:0)

我就是这样做的

Option Explicit

Const wdFormatXMLDocument As Integer = 12

Sub tester()
    Dim wordApp As Object, wordDoc As Object
    Dim appendDate As String, FName As String

    Set wordApp = CreateObject("Word.Application")

    wordApp.Visible = True

    appendDate = "Y"
    FName = "robot"

    If UCase(appendDate) = "Y" Then  '<~~ Unsure of this as you are already setting the value of Y
        FName = ThisWorkbook.Path & "\" & FName & "-" & Format(Now(), "yyyymmdd-hhmm") & ".docx"
    Else
        FName = ThisWorkbook.Path & "\" & FName & ".docx"
    End If

    Set wordDoc = wordApp.Documents.Add

    ThisWorkbook.Sheets("Sheet1").ChartObjects(1).Activate
    ActiveChart.ChartArea.Copy
    wordApp.Selection.PasteSpecial Link:=False, DataType:=0, Placement:=0

    wordDoc.SaveAs2 Filename:=FName, FileFormat:=wdFormatXMLDocument

    wordDoc.Close (False)

    wordApp.Quit

    Set wordDoc = Nothing
    Set wordApp = Nothing
End Sub

<强>截图

enter image description here

答案 1 :(得分:0)

由于您退出Word.Application,因此不再有wordApp,因此Documents.Open没有可执行的环境。

如果您想在任何时候直接打开文件,而无需先启动应用程序,您可以使用GetObject

设置wordDoc = GetObject(FName)

如果您需要在稍后使用GetObject打开文件后解决Word.Application:

Set wordApp = wordDoc.Application