Restricting the user to delete the cell contents

不羁岁月 提交于 2020-01-06 20:09:56

问题


Is there's any way to restrict the user from deleting the cell contents without using the protect method of excel. I have this code:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")
    If Not Intersect(Target, Range("C21:D" & ws.Range("C" & ws.Rows.Count).End(xlUp).Row)) Is Nothing Then
         Cancel = True
         MsgBox "You are not allowed to edit!", vbCritical + vbOKOnly
    EndIf
End sub

But this only disallows the editing of the cell contents. I want make a function that would disallow the editing and deleting the data in a cell without using the protect method. Thanks!


回答1:


Without lock and unlock, you can use this. We have there one global variable to store selection value (to preserve beforechange state). Function SelectionChange, updating value of current cell, so we can restore cell value after users try.

Sub worksheet_change just controling, if user targeting specified row and column (can be adjusted for whole range), and if he try to change value, he is prompted and value is set back.

Dim prevValue As Variant

Private Sub worksheet_SelectionChange(ByVal target As Range)

    prevValue = target.Value

End Sub

Private Sub worksheet_change(ByVal target As Range)



    If target.Row = 5 And target.Column = 5 Then

        If target.Value <> prevValue Then
            target.Value = prevValue


            MsgBox "You are not allowed to edit!", vbCritical + vbOKOnly

        End If

    End If


End Sub

edit: disable editing every cell which is not empty

Private Sub worksheet_change(ByVal target As Range)



    If prevValue <> "" Then

        If target.Value <> prevValue Then
            target.Value = prevValue


            MsgBox "You are not allowed to edit!", vbCritical + vbOKOnly

        End If

    End If


End Sub


来源:https://stackoverflow.com/questions/35838370/restricting-the-user-to-delete-the-cell-contents

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