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

D. O. picture D. O. · Nov 29, 2016 · Viewed 11.6k times · Source

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 

Answer

JNevill picture JNevill · Nov 29, 2016

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