Skipping Password-Protected Documents in a Batch Process

Article contributed by Ibby

The Documents.Open method has a PasswordDocument parameter where you can specify the password of the document to be opened. If you put in a nonsense password (i.e.: one that is unlikely to be used by any sane person as a password!), you will observe the following behaviour:

 

If the document has no password assigned, the Documents.Open method ignores the PasswordDocument parameter and the document is opened normally.

 

If the document has a password, the password specified in the PasswordDocument will be wrong, generating an error 5408 "The password is incorrect....". You can trap this error and loop back to the next file to be opened. The following is an example of how to trap this error.

Option Explicit
 
Public Sub ProcessBatch()
 
Dim strFileName As String
Dim strFilePath As String
Dim oDoc As Document
   
    ' Set Directory for Batch Process
    strFilePath = "C:\Test\"
   
    ' Get Name of First .doc File from Directory
    strFileName = Dir$(strFilePath & "*.doc")
   
 
    While Len(strFileName) <> 0
   
        ' Set Error Handler
        On Error Resume Next
               
        ' Attempt to Open the Document
        Set oDoc = Documents.Open( _
                   FileName:=strFilePath & strFileName, _
                   PasswordDocument:="?#nonsense@$")
       
        Select Case Err.Number
            Case 0
                ' Document was Successfully Opened
                Debug.Print strFileName & " was processed."

            Case 5408
                ' Document is Password-protected and was NOT Opened
                Debug.Print strFileName & " is password-protected " & _
                    "and was NOT processed."
                ' Clear Error Object and Disable Error Handler
                Err.Clear
                On Error GoTo 0
                ' Get Next Document
                GoTo GetNextDoc

            Case Else
                ' Another Error Occurred
                MsgBox Err.Number & ":" & Err.Description
        End Select
       
        ' Disable Error Handler
        On Error GoTo 0
       
        '-------------------------------------
        '-------------------------------------
        '---Perform Action on Document Here---
        '-------------------------------------
        '-------------------------------------
       
        ' Close Document
        oDoc.Close
       
        ' Clear Object Variable
        Set oDoc = Nothing
       
GetNextDoc:
       
        ' Get Next Document from Specified Directory
        strFileName = Dir$()
 
    Wend
   
End Sub


Click to view Terms of Use page

Click to view Disclaimer page