Excel VBA - Check if a worksheet is protected WITH A PASSWORD

前端 未结 1 1511
既然无缘
既然无缘 2021-01-19 12:06

We can check if a sheet is protected using ProtectContents property. But how check if it is protected with a password?

if ws.ProtectContents then
    \'\'do          


        
相关标签:
1条回答
  • 2021-01-19 12:57

    I don't believe there is a direct way of doing this by way of a property. Alternatively, though, you could attempt to unprotect the worksheet with a blank password and catch the error should it fail:

    Function isSheetProtectedWithPassword(ws As Worksheet) As Boolean
        If ws.ProtectContents Then
            On Error GoTo errorLabel
            ws.Unprotect ""
            ws.Protect
        End If
    errorLabel:
        If Err.Number = 1004 Then isSheetProtectedWithPassword = True
    End Function
    

    You can call this like:

    isSheetProtectedWithPassword(Worksheets("Sheet1"))
    

    And it will return True or False

    0 讨论(0)
提交回复
热议问题