取消保护多个工作簿 VBA

Unprotecting multiple workbooks VBA

我正在尝试从一个文件中解锁多个 Excel Workbooks。我知道密码并且所有文件都相同。

我运行下面的代码。它的工作原理是我没有收到错误消息并且所有正确的工作簿都打开然后关闭。但是,当我尝试在 运行 设置代码后手动打开文件时,系统仍然要求我输入密码。

我的 ActiveWorkbook.Unprotect 不能单独工作,我真的不明白为什么,因为我在互联网上没有看到不同的语法。

这是我的代码:

Sub Hell3()
    Dim WB As Workbook
    Dim xFd As FileDialog
    Dim xFdItem As Variant
    Dim xFileName As String
    Set xFd = Application.FileDialog(msoFileDialogFolderPicker)

    If xFd.Show = -1 Then
        xFdItem = xFd.SelectedItems(1) & Application.PathSeparator
        xFileName = Dir(xFdItem & "*.xls*")
        Do While xFileName <> ""
            Workbooks.Open (xFdItem & xFileName), Password:="pass"
            ActiveWorkbook.Unprotect Password:="pass"
            xFileName = Dir
        Loop
    End If

    Dim macrowb As String
    macrowb = "Book1.xlsm"
    For Each WB In Application.Workbooks
        If WB.Name <> macrowb Then
            WB.Close SaveChanges:=True
        End If
    Next WB
End Sub

使用 ActiveWorkbook 经常会导致问题。这就是为什么一般的建议是避免它,而是明确地引用每个工作簿。您假设打开工作簿时,它会成为活动的。

编辑:由于您现在已经阐明要删除的是文件保护(不是工作簿保护),您需要使用另存为,并从中删除密码保护文件 - 如下

试试这个:

Do While xFileName <> ""
    Set wb = Workbooks.Open(xFdItem & xFileName, Password:="pass")
    wb.Unprotect Password:="pass" ' This explicitly unprotects the opened workbook.
    xFileName = Dir
    wb.SaveAs Filename:=xFdItem & xFileName, FileFormat:=xlOpenXMLStrictWorkbook, Password:=""
Loop

更多信息: https://docs.microsoft.com/en-us/office/vba/api/excel.workbook.saveas

这将有效:

Sub Hell3()
    Dim WB As Workbook
    Dim xFd As FileDialog
    Dim xFdItem As Variant
    Dim xFileName As String
    Set xFd = Application.FileDialog(msoFileDialogFolderPicker)

    If xFd.Show = -1 Then
        xFdItem = xFd.SelectedItems(1) & Application.PathSeparator
        xFileName = Dir(xFdItem & "*.xls*")
        MkDir xFdItem & "\Password Removed Files"
        Do While xFileName <> ""
            Set WB = Workbooks.Open((xFdItem & xFileName), Password:="pass")

                WB.SaveAs Filename:=xFdItem & "Password Removed Files\" & xFileName, FileFormat:=51, Password:="", WriteResPassword:="", _
                ReadOnlyRecommended:=False, CreateBackup:=False

                WB.Close True

            xFileName = Dir
        Loop
    End If


End Sub

将使用密码删除的文件创建一个新文件夹