Link to home
Start Free TrialLog in
Avatar of mrherndon
mrherndon

asked on

Excel: Protect Cell After Data Entry

I have a spreadsheet with columns B and L.  For any entry in columns B or L, I would like the cell to be protected as soon as input complete.

So, if a value is entered into B2, it should be protected.  But when the user moves to B3, that cell should be still open for input while B2 is locked.

Can someone help?
Avatar of krishnakrkc
krishnakrkc
Flag of India image

In the sheet module

Option Explicit

Dim blnUnlockedAllCells As Boolean
Private Sub Worksheet_Change(ByVal Target As Range)
    
    Const RangeToLock As String = "B:B,L:L" '<<  adjust to suit
    
    If Target.Cells.Count > 1 Then Exit Sub
    
    If Not blnUnlockedAllCells Then
        Me.Cells.Locked = False
        On Error Resume Next
        Me.Range(CStr(RangeToLock)).SpecialCells(2).Locked = True
        On Error GoTo 0
        blnUnlockedAllCells = True
        Me.Protect Password:="pwd", userinterfaceonly:=True
    End If
    
    If Not Application.Intersect(Target, Me.Range(CStr(RangeToLock))) Is Nothing Then
        If Len(Target) Then Target.Locked = True
    End If
    
End Sub

Open in new window


Kris
Avatar of Rob Henson
Using Worksheet Change Event is good in some cases but the downside is that you lose your Undo History.

So in this case, what happens if the users realises that they have entered the wrong value in B2? The Change Event locks it and they can't change it. They can't just do an Undo either because a macro has run.

Thanks
Rob H
Avatar of mrherndon
mrherndon

ASKER

Thanks very much.  I see where the sheet module example given could work well for me.

Question:  how best to combine two different subroutines on the same sheet module?  I have another in place now, which I use to control point of focus.  How best to combine the below with the proposed solution?

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Cells.Count = 1 Then
        Application.EnableEvents = False
        If Target.Column = 1 Then
            Target.Offset(0, 1).Value = VBA.Now
            Target.Offset(0, 10).Select
        ElseIf Target.Column = 11 Then
            Target.Offset(1, -10).Select
        End If
        Application.EnableEvents = True
    End If
End Sub

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of krishnakrkc
krishnakrkc
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hello,

I have spreadsheet with range of A3:AN219, i would like the cell protected as soon as input complete.
I tried above solution but i did not get any solution for my problem.

Please help me on this