这是您可能的解决方法。这个想法是将任何不正确的密码传递给WriteResPassword argument
. 如果文件受到保护,则会抛出错误。如果是这样,您将能够识别该文件并以read-only mode
. 或者,其他文件的密码将被忽略,并且将为read-write mode
.
下面代码中的一些附加注释。
Sub PossibleWorkaround()
Dim Pass As String
'any password
Pass = "blahblah"
'file which is write-protected will throw error during opening it _
with incorrect password
On Error Resume Next
Workbooks.Open "c:\users\alpha\desktop\filename.xlsx", , , , , Pass
If Err.Number = 1004 Then
'if so, try to open it in read-only mode
Workbooks.Open "c:\users\alpha\desktop\filename.xlsx", , True
End If
'return to standard error handling or set as expected
On Error GoTo 0
'the same for file which is not write-protected
'incorrect password will be ignored
On Error Resume Next
Workbooks.Open "c:\users\alpha\desktop\filename A.xlsx", , , , , Pass
If Err.Number = 1004 Then
'therefore this if statement will not be called
Workbooks.Open "c:\users\alpha\desktop\filename.xlsx", , True
End If
On Error GoTo 0
End Sub