在锁定的工作表上时如何显示错误消息

时间:2019-06-17 04:32:24

标签: excel vba

我有一个代码,可以从锁定的工作表中删除一个值。每当我运行代码时,都会出现错误消息

  

Range类的删除方法失败

显示

。如何用诸如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

1 个答案:

答案 0 :(得分:-1)

这将起作用:

Activesheet.ProtectContents会告诉您工作表是否受到保护。

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