2016-05-31 167 views
1

我試圖在指定位置打開Word應用程序,編輯,保存並需要檢查用戶是否輸入了正確的文件名。 這裏是我的代碼EXCEL VBA在指定位置打開Word,Edit和Saveas。

Dim Doc 
Dim DocPath 
Dim DocObj 
Dim VarResult 

DocPath = "C:\MyFolder\MyDocument.doc"  
Set DocObj = CreateObject("word.Application") 
Doc = DocObj.Documents.Open(DocPath) 
DocObj.Visible = True 

打開文檔後,我做了一些變化

With Doc.ActiveDocument 
Set myRange = .Content 
With myRange.Find 
.Execute FindText:="FindText", ReplaceWith:="ReplaceText", Replace:=2 
End With 
End With 

現在,我已經在另存爲一個問題的文件。我使用了兩種替代方法: 1:GetSaveAsFilename,2:SaveAs。我需要顯示Saveas對話框(使用所有DefaultLocation,InitialFilename,DocumentType,Title屬性)。用戶需要選擇和需要驗證的相同,無論用戶是否沒有給出取消按鈕。

varResult = Doc.GetSaveAsFilename(_ 
FileFilter:="DP Document (*.doc), *.doc, DP Document (*.docx), *.docx", Title:="Save DP", initialvalue:="InitialDocument") 
If varResult <> False Then 
MsgBox "File choosen = " & varResult 
Else 
MsgBox "Please select the file" 
End If 

我得到運行時錯誤。提前致謝。

回答

0

根據此Microsoft Article,「如果您使用CreateObject函數與Word.Application或Word.Basic類型的對象,該函數將失敗,如果Word已在運行。」失敗由運行時錯誤指示。微軟建議你「檢查Word是否已經在運行,如果沒有,請啓動一個新的Word實例。」例如,您可以使用「GetObject函數創建一個Word.Application對象,如果GetObject函數失敗,Word將不會運行,因此CreateObject函數將用於設置Word.Application對象。」鏈接文章中提供的代碼如下:

Sub RunWord() 

    Dim wObj As Word.Application 
    On Error Resume Next 

    ' Get existing instance of Word if it exists. 
    Set wObj = GetObject(, "Word.Application") 

    If Err <> 0 Then 
     ' If GetObject fails, then use CreateObject instead. 
     Set wObj = CreateObject("Word.Application") 
    End If 

    ' Add a new document. 
    wObj.Documents.Add 

    ' Exit Word. 
    wObj.Quit 

    ' Clear object memory. 
    Set wObj = Nothing 

End Sub