2016-04-12 61 views
0

此函數創建一個word文檔,保存並關閉它,但在嘗試重新打開時失敗。它說這在遠程通話不起作用。重新打開單詞文檔的適當做法是什麼?還是沒有必要再關閉和打開? word和excel之間的交流似乎很困難。如何將圖表從Excel傳輸到Word

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 
+0

你不需要重新創建一個對象,然後用'設置wordDoc'因爲你是對之前退出應用程序? – Dan

+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

+0

感謝您的信息。我試過這個,當這行代碼運行時出現錯誤「word app has stopped working」:'wordApp.Selection.PasteSpecial Link:= False,DataType:= wdPasteOLEObject,Placement:= wdInLine' – teepee

+0

我剛測試過它,它工作的很好 –

+0

嗯。我在Windows 7上運行的是2010版本。這是否意味着我需要在那裏更改任何內容? – teepee

0

既然你退出,然後一個Word.Application有沒有更多的wordApp,所以Documents.Open沒有要執行的環境。

如果你想在任何時候打開一個文件,直接,沒有先啓動應用程序,你可以使用GetObject

設置wordDoc = GetObject的(FName參數)

如果您需要解決的話。在以後的應用程序,在將GetObject打開文件後:

Set wordApp = wordDoc.Application 
相關問題