需一次將大量 Word 文件中的特定文字全部取代?撰寫 VBA 巨集搭配檔案搜尋功能即可實現批次處理。
Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
Dim myPas As String, myPath As String, i As Integer, myDoc As Document
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "選擇目標資料夾"
If .Show = -1 Then
myPath = .SelectedItems(1)
Else
Exit Sub
End If
End With
myPas = InputBox("請輸入開啟密碼(無則留白):")
With Application.FileSearch
.LookIn = myPath
.FileType = msoFileTypeWordDocuments
If .Execute > 0 Then
For i = 1 To .FoundFiles.Count
Set myDoc = Documents.Open(FileName:=.FoundFiles(i), PasswordDocument:=myPas)
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "OfficeStudy" ' 要尋找的文字
.Replacement.Text = "www.dzwebs.com" ' 取代為
.Forward = True
.Wrap = wdFindAsk
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchByte = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
myDoc.Save
myDoc.Close
Set myDoc = Nothing
Next
End If
End With
Application.ScreenUpdating = True
End Sub
.Text = "OfficeStudy" ' 改為實際尋找文字
.Replacement.Text = "www.dzwebs.com" ' 改為實際取代文字
注意:此程式碼使用舊版 FileSearch 物件,Word 2007 後已棄用,新版建議改用 FileSystemObject 或 Dir 函數遞迴遍歷資料夾。但邏輯核心(開啟→尋找取代→儲存→關閉)不變。