
我正在嘗試建立一個巨集,以便在多個 Word 文件中進行批次查找和替換。我在網上找到了這個文件,並將其更改為也適用於圖形,但是我不斷收到運行時錯誤(5174),指出找不到該文件(即使它肯定在文件夾中)。
我相信問題是這樣的:support.microsoft.com/en-us/kb/212664,但在將其實現到我的巨集中時遇到了一些麻煩,因為在每個Fname 之後簡單地添加“.docx”似乎不起作用。
我對宏的經驗有限,所以如果這是一個新手問題,我深表歉意。
任何幫助將不勝感激。
謝謝。
Sub ReplaceText()
Dim Directory As String
Dim FType As String
Dim FName As String
Directory = "C:\Users\pieria\Desktop\TempPics"
FType = "*.docx"
ChDir Directory
FName = Dir(FType)
' for each file you find, run this loop
Do While FName <> ""
' open the file
Documents.Open FileName:=FName '<--Error is supposedly here
' search and replace the company name
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "CompanyA"
.MatchCase = True
.Replacement.Text = "CompanyB"
End With
Selection.Find.Execute Replace:=wdReplaceAll
' save and close the current document
ActiveDocument.Close wdSaveChanges
' look for next matching file
FName = Dir
Loop
End Sub
答案1
我預計當前實例不知道ChDir
您所做的事情。開啟檔案時最好指定完整路徑:
' open the file
Documents.Open FileName:= Directory & "\" & FName
我將字串Directory
與FName
運算子連接起來&
。
因此,如果Directory
containsC:\Users\pieria\Desktop\TempPics
和FName
containsFirst.docx
一起&
創建一個新字串C:\Users\pieria\Desktop\TempPics\First.docx
請注意\
我在目錄名稱和檔案名稱之間添加了...