我正在尝试创建一个函数来检查 docx 或 pptx 文件是否受密码保护。这是我的功能:
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
我确实可以工作,但有时不可靠,它只会抛出以下错误:
isPasswordProtected():The remote server machine does not exist or is unavailable
而不是:
isPasswordProtected( ):The password is incorrect. Word cannot open the document.
(C:\Temp\word\protected.docx)
False
isPasswordProtected( ):
True
当我检查大量文件时,这是一个问题。有没有其他方法可以做到这一点?
尝试这个版本的函数
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
提示:如果未受保护,MS Office 文件以“PK”字节开头(zip 格式)