从Excel文件中删除密码

时间:2018-12-21 13:28:28

标签: excel vba passwords

我在一个文件夹中大约有400个Excel文件(有些是.xls,有些是.xlsx)。

如何使用VBA代码从这些文件中删除密码?

1 个答案:

答案 0 :(得分:1)

从.xls *文件中删除工作簿密码

我想您知道密码,并且所有文件中的密码都是相同的。

方法:

它循环浏览文件夹中的所有文件,并以cStrExtensions中指定的扩展名打开每个文件,删除密码,然后保存并关闭它。

用法:

运行代码,这将打开“文件夹选择器”对话框,然后导航到文件所在的文件夹(看不到它们)并按OK。

Sub RemovePassword()

  ' String Lists
  Const cStrExtensions As String = "*.xls*"
  Const cStrPassword As String = "123"

  Dim strFolderPath As String     ' Search Folder
  Dim strFileName As String       ' Current File Name (Workbook)

  With Application
    .ScreenUpdating = False
    .DisplayAlerts = False
  End With

  On Error GoTo ProcedureExit

  With ThisWorkbook.ActiveSheet

    ' Choose Search Folder
    With Application.FileDialog(msoFileDialogFolderPicker)
      If .Show = False Then Exit Sub
      strFolderPath = .SelectedItems(1) & "\"
    End With

    ' Loop through folder to determine Current File Name (Workbook).
    strFileName = Dir(strFolderPath & cStrExtensions)

    ' Loop through files in folder.
    Do While strFileName <> ""

      ' Open each file in folder
      Workbooks.Open strFolderPath & strFileName

      With ActiveWorkbook
         .Unprotect cStrPassword
         .Close True
      End With

      strFileName = Dir()
      ' Exclude this workbook.
      If .Parent.Name = strFileName Then strFileName = Dir()

    Loop

  End With

ProcedureExit:

  With Application
    .ScreenUpdating = True
    .DisplayAlerts = True
  End With

End Sub