忽略受密码保护的Excel文件

时间:2014-06-15 00:33:50

标签: excel-vba vba excel

我正在迭代一个充满.xlsx文件的目录。我正在使用VBA打开它们并调整几列。他们中的一些人要求输入密码,我不知道,所以我只想跳过这些文件然后转到下一个。如何在VBA中实现这一目标?我试过以下但没有运气。

Set openedBook = Workbooks.Open(File, IgnoreReadOnlyRecommended:=True)

enter image description here

这是我得到的错误的图像 - 如何完全忽略工作簿或VBA点击"取消"在提示?

1 个答案:

答案 0 :(得分:1)

您可以尝试传递(已知的无效)密码并使用错误处理来忽略失败

像这样的东西

Sub Demo()
    Dim openedBook  As Workbook
    Dim sFile As String

    sFile = "C:\Your\File\Name.xlsx"

    Set openedBook = Nothing ' in case openedBook was previously set to somthing

    On Error Resume Next
    Set openedBook = Workbooks.Open( _
      FileName:=sFile, _
      IgnoreReadOnlyRecommended:=True, _
      Password:="!")

    On Error GoTo 0

    If Not openedBook Is Nothing Then
        ' do your stuff
    Else
        ' For demo purposes only
        MsgBox "File " & sFile & " is password protected"
    End If

End Sub