vbams-wordpowerpoint

Is there any reliable way to check if powerpoint and word documents are password protected in VBA?


I am trying to create a function that would check if docx or pptx files are password protected. Here is my function:

 Public Function isPasswordProtected(ByVal path As String) As Boolean
    On Error GoTo ErrorHandler
    Dim wordApp As Word.Application
    Dim wordFile As Object
    
    
    Set wordApp = New Word.Application
    wordApp.Visible = False
 
    Set wordFile = Documents.Open(fileName:=path, PasswordDocument:="!@#$%")
    If Err = 0 Then ' no error occurred
        isPasswordProtected = False
    Else
        isPasswordProtected = True
    End If
    
    wordFile.Close (False)
    wordApp.Quit
    Set wordApp = Nothing
    Set wordFile = Nothing
    isPasswordProtected = True
ErrorHandler:
    Debug.Print "isPasswordProtected( ):" & Err.Description
End Function

Sub TestProtection()

    Dim protected As String
    Dim unrpotected As String
    
    protected = "C:\Temp\word\protected.docx"
    Debug.Print isPasswordProtected(protected)
    unrpotected = "C:\Temp\word\unprotected.docx"
    Debug.Print isPasswordProtected(unrpotected)
    
End Sub

I does work but not reliably from time to time it just throws the following error: isPasswordProtected():The remote server machine does not exist or is unavailable

Rather than:

isPasswordProtected( ):The password is incorrect. Word cannot open the document.
 (C:\Temp\word\protected.docx)
False
isPasswordProtected( ):
True

And when I am checking lots of documents its a problem. Are there any alternative ways of doing that?


Solution

  • Try this version of your function

     Public Function isPasswordProtected(ByVal path As String) As Boolean
        On Error GoTo ErrorHandler
        Dim wordApp As Word.Application
        Dim wordFile As Word.Document
        
        
        Set wordApp = New Word.Application
        wordApp.Visible = False
     
        Set wordFile = wordApp.Documents.Open(Filename:=path, PasswordDocument:="!@#$%")
        If Err = 0 Then ' no error occurred
            isPasswordProtected = False
        Else
            isPasswordProtected = True
        End If
        
        wordFile.Close (False)
        wordApp.Quit
        Set wordApp = Nothing
        Set wordFile = Nothing
    Exit Function
    ErrorHandler:
        Debug.Print "isPasswordProtected( ):" & Err.Description & vbNewLine
        wordApp.Quit
        Set wordApp = Nothing
        Set wordFile = Nothing
        isPasswordProtected = True
    End Function