I have told my Excel not to move after ENTER, so that's why it worked on my
system. Thanks Gord for pointing this out.
To fix this problem (I think) I have a better idea, which doesn't have to
take into account the cursor movements after ENTER (which anyway cannot be
anticipated because they depend on each individual user's setup). Instead of
running the code from the cell where Excel jumps after ENTER (ActiveCell)
the code runs from the cell where the input was made (Target). I've
modified the code, added 2 lines for better maintenance and readability and
made the message clearer.
As I wrote before: The code needs finetuning, e.g. a proper error handling.
In any case you should make sure to password protect your macro, otherwise
your worksheet password can be picked up by anybody clever enough to hit
Alt+F11.
Here is the new version. Let me know if it works.
Cheers,
Joerg Mochikun
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
'Define worksheet and cells that cause locking of other cells
Set TriggerCells = Worksheets("Sheet1").Range("C4:C33")
'Define row to be locked. From Target (=input cell) to 9 columns to the
right
Set LockedRow = Range(Target, Target.Offset(0, 9))
'Exit macro if input was not made in one of the trigger cells
If Application.Intersect(Target, TriggerCells) Is Nothing Then Exit Sub
'Unprotect sheet so that cell format can be changed to locked
ActiveSheet.Unprotect
'Lock all cells from Target (=input cell) up to 9 columns to the Right
LockedRow.Locked = True
'Protect sheet again
ActiveSheet.Protect
'Give feedback to user
MsgBox LockedRow.Address(False, False) & " is now protected. To
unprotect call the manager!"
End Sub
Gord Dibben said:
When you type in C4 then hit ENTER, the ActiveCell is now C5 and the code runs
from there.
Either set your ENTER key to not move or alter the code as below where I have
moved up one row from the activecell with offset(-1 , 0) and offset(-1, 9)
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
'Define worksheet and cells that cause locking of other cells
Set TriggerCells = Worksheets("Sheet1").Range("C4:C33")
'Exit macro if input was not made in one of the trigger cells
If Application.Intersect(ActiveCell, TriggerCells) Is Nothing Then Exit Sub
'Unprotect sheet so that cell format can be changed to locked
ActiveSheet.Unprotect
'Unlock all cells from (=input cell) up to 9 columns to
'the Right
Range(ActiveCell.Offset(-1, 0), _
ActiveCell.Offset(-1, 9).Resize).Locked = True
'Protect sheet again
ActiveSheet.Protect
'Give feedback to user
MsgBox "Row is now protected. To unprotect call the manager!"
End Sub
Gord Dibben MS Excel MVP