简体   繁体   中英

MsgBox when user tries to delete a row

I am building a tool in excel and have protected the workbook so that deleting or inserting rows/columns is not allowed, using the code below:

Sub ProtectSheet()
ActiveSheet.Protect _
    DrawingObjects:=False, _
    Contents:=True, _
    Scenarios:=False, _
    AllowFormattingCells:=True, _
    AllowFormattingColumns:=True, _
    AllowFormattingRows:=True, _
    AllowInsertingHyperlinks:=True, _
    AllowInsertingColumns:=False, _
    AllowInsertingRows:=False, _
    AllowDeletingColumns:=False, _
    AllowDeletingRows:=False, _
    AllowSorting:=True, _
    AllowFiltering:=True, _
    AllowUsingPivotTables:=True, _
    Password:=cPassword
End Sub

However, I also want a message box to appear if the user tries to delete or insert a row/column that tells them they cannot do this and provides other instructions. Can anyone advise me on how to do this?

Thanks!

You can use the selection change event like this (code to go in the worksheet's code module):

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    With Target
        If .Address = .EntireRow.Address Or .Address = .EntireColumn.Address Then
            MsgBox "You can not insert or delete any row or column", vbInformation, "FYI"
        End If
    End With
End Sub

If they try to insert or delete by selecting entire rows or columns (which is how I typically go about doing that) then this message box will pop up, but it won't pop up if you select smaller ranges of cells.

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