简体   繁体   中英

Open password protected file

I want to check if file is password protected. The below code is working fine. But I workbook is password protected, please advise as to where to put the password in below code

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

I presume you want to open the file as subject of your post mentions. To open the file as per VBA Help

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

Hence, usage:

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

To determine if a workseet or a workbook is protected

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

To un-protect a workbook:

'------------------------------------------------------------------------------------------

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

'------------------------------------------------------------------------------------------

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM