简体   繁体   中英

Check if a Sheet is Protected in Excel using VBA

I have a code which deletes a value from a locked sheet. Whenever I run the code, Error message

Delete method of Range class failed

is displayed. How do I prompt the user with a message such as first unprotect the sheet ?

Sub DeleteRow()
    Dim rng As Range

    On Error Resume Next
    With Selection.Cells(1)
        Set rng = Intersect(.EntireRow, ActiveCell.ListObject.DataBodyRange)
        On Error GoTo 0
        If rng Is Nothing Then
            MsgBox "Please select a valid table cell.", vbCritical
        Else
            rng.delete xlShiftUp
        End If
    End With
End Sub

This will Work:

Activesheet.ProtectContents will tell you if a sheet is protected or not.

Sub DeleteRow()

    Dim rng As Range

    On Error Resume Next

    If ActiveSheet.ProtectContents = False Then

        With Selection.Cells(1)
            Set rng = Intersect(.EntireRow, ActiveCell.ListObject.DataBodyRange)
            On Error GoTo 0
            If rng Is Nothing Then
                MsgBox "Please select a valid table cell.", vbCritical
            Else
                rng.Delete xlShiftUp
            End If
        End With

    Else: MsgBox "Unprotect the Sheet First!"

    End If

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