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

心不动则不痛 提交于 2020-03-01 15:10:49

问题


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 something
end if 

回答1:


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



来源:https://stackoverflow.com/questions/40874165/excel-vba-check-if-a-worksheet-is-protected-with-a-password

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!