我正在尝试从一个文件中解锁多个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
答案 0 :(得分:2)
使用ActiveWorkbook通常会导致问题。这就是为什么通常的建议是避免使用它,而是显式地引用每个工作簿。您假设打开一个工作簿后,它便成为活动工作簿。
编辑:由于您现在已经阐明要删除的是文件保护(而不是工作簿保护),因此需要使用SaveAs,并从文件中删除密码保护-如下所示
尝试一下:
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
答案 1 :(得分:2)
这将起作用:
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
将使用密码删除的文件创建一个新文件夹