【问题标题】:Open password protected file打开受密码保护的文件
【发布时间】:2015-08-08 05:49:35
【问题描述】:

我想检查文件是否受密码保护。下面的代码工作正常。但是我的工作簿是受密码保护的,请告知在下面的代码中将密码放在哪里

Sub Example1()

    If GetAttr("c:\test.xls") And vbReadOnly Then
        MsgBox "File is Read-only"
    Else
        MsgBox "File is not read-only"
    End If

End Sub

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    我想您想将文件作为帖子提及的主题打开。 根据 VBA 帮助打开文件

    expression.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad) 
    

    因此,用法:

    Workbooks.Open Filename:= "C:\Documents and Settings\My Documents\Book2.xls", Password:="YourPasswordHere"
    

    【讨论】:

      【解决方案2】:

      确定工作集或工作簿是否受保护

      Option Explicit
      
      Public Function isSheetProtected(Optional ByRef ws As Worksheet = Nothing) As Boolean
      
          If ws Is Nothing Then Set ws = Application.ActiveSheet
      
          isWorksheetProtected = ws.ProtectContents Or _
                                 ws.ProtectDrawingObjects Or _
                                 ws.ProtectScenarios
      
      End Function
      

      Public Function isFileProtected(Optional ByRef wb As Workbook = Nothing) As Boolean
      
          If wb Is Nothing Then Set wb = Application.ActiveWorkbook
      
          isWorkbookProtected = ws.ProtectWindows Or ws.ProtectStructure
      
      End Function
      

      要取消保护工作簿:

      '------------------------------------------------------------------------------------------
      
      Public Sub unprotectFile(Optional ByRef wb As Worksheet = Nothing)
      
          If wb Is Nothing Then Set wb = Application.ActiveWorkbook
      
          If isFileProtected(wb) Then wb.Unprotect Password:="YourPassword"
      
      End Sub
      
      '------------------------------------------------------------------------------------------
      

      【讨论】: