萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 辦公室軟體 >  >> Word 教學 >> Word 使用技巧

Word VBA:批次開啟指定資料夾所有 .doc 文件並套用保護

需對某資料夾下所有 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 → .docx:在迴圈內呼叫 doc.SaveAs2 ... wdFormatXMLDocument 並刪除原檔。
  • 批次列印:doc.PrintOut。
  • 批次搜尋/取代:使用 doc.Content.Find.Execute Replace:=wdReplaceAll。
  • 批次提取文字存入資料庫/Excel:迴圈寫入 Workbooks 或 ADO 連線。

⚠ 重要提醒

  1. 備份原始檔案:批次修改具破壞性,務必先複製整個資料夾備份。
  2. .doc 格式限制:Word 2007+ 開啟 .doc 會觸發相容模式,巨集執行速度較慢;建議先轉 .docx 再處理。
  3. 密碼管理:代碼中明文密碼僅供測試,正式環境請用 InputBox 讓使用者輸入或從安全儲存讀取。
copyright © 萬盛學電腦網 all rights reserved