需對某資料夾下所有 Word 97-2003 文件(.doc)執行相同操作(如加密保護、列印、轉檔)時,可使用 Dir 函數配合 Documents.Open 進行批次處理。本文提供標準範本代碼並說明關鍵細節。
Sub BatchProcessDocFiles()
Dim folderPath As String
Dim fileName As String
Dim doc As Document
' 1. 選擇目標資料夾(使用 FileDialog 讓使用者互動選擇)
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "請選擇包含 .doc 文件的資料夾"
If .Show = -1 Then
folderPath = .SelectedItems(1)
Else
Exit Sub ' 使用者取消
End If
End With
' 2. 確保路徑以 \ 結尾
If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\"
' 3. 取得第一個 .doc 檔案
fileName = Dir(folderPath & "*.doc")
Application.ScreenUpdating = False
' 4. 迴圈處理每個檔案
Do While fileName <> ""
Set doc = Nothing
On Error Resume Next
Set doc = Documents.Open(FileName:=folderPath & fileName, _
ConfirmConversions:=False, _
ReadOnly:=False, _
PasswordDocument:="YourPassword") ' 若需開啟密碼
On Error GoTo 0
If Not doc Is Nothing Then
' === 在此處放入您要對每個文件執行的操作 ===
' 範例:套用表單保護
doc.Protect Type:=wdAllowOnlyFormFields, Password:="ProtectPwd"
' 範例:另存為 .docx
' doc.SaveAs2 FileName:=Replace(doc.FullName, ".doc", ".docx"), FileFormat:=wdFormatXMLDocument
doc.Close SaveChanges:=wdSaveChanges
Set doc = Nothing
End If
fileName = Dir() ' 取得下一個檔案
Loop
Application.ScreenUpdating = True
MsgBox "批次處理完成!", vbInformation
End Sub
| 項目 | 說明 |
|---|---|
FileDialog(msoFileDialogFolderPicker) | 讓使用者以圖形介面選擇資料夾,避免硬編碼路徑。 |
Dir(folderPath & "*.doc") | 取得第一個符合條件的檔名;後續 Dir() 不帶參數可繼續取得下一個。 |
Documents.Open 參數 | ConfirmConversions:=False 避免轉換確認對話框;PasswordDocument 若檔案有開啟密碼需提供。 |
On Error Resume Next | 單一檔案開啟失敗(損毀、被鎖定)不中斷整個迴圈。 |
doc.Close SaveChanges:=wdSaveChanges | 確保修改寫入磁碟;若唯讀開啟則用 wdDoNotSaveChanges。 |
doc.SaveAs2 ... wdFormatXMLDocument 並刪除原檔。doc.PrintOut。doc.Content.Find.Execute Replace:=wdReplaceAll。Workbooks 或 ADO 連線。