簡體   English   中英

EXCEL VBA在指定位置打開Word,編輯和Saveas。

[英]EXCEL VBA to Open Word, Edit and Saveas in the specified location.

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

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

現在,我在saveas文件中遇到了問題。 我使用了兩種替代方法,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

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

根據此Microsoft文章 ,“如果您將CreateObject函數與Word.Application或Word.Basic類型的對象一起使用,則如果Word已在運行,則該函數將失敗。” 失敗由運行時錯誤指示。 Microsoft建議您“檢查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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM