Locking a cell is to prevent alteration of cell contents.
In excel go to Format|Cells... then select Protection tab and ensure the Locked tick box is Unchecked for your destination range of cells. Then use the Tools|Protection|Protect Sheet... to protect the sheet and any unlocked cells will be locked against alteration when the worksheet change.
Code:
This is a worksheet event code, which means that it needs to be placed in the appropriate worksheet code module, not a standard code module.
Option Explicit
Public Sub Worksheet_Change(ByVal Target As Range)
Call ApplyProtection(Range("A1:B20"))
Sheets("Sheet1").Protect Password:="password", UserInterfaceOnly:=True
End Sub
Private Sub ApplyProtection(thisRange As Range)
Dim thisCell As Range
ActiveSheet.Unprotect Password:="password"
For Each thisCell In thisRange
If IsEmpty(thisCell) Then
thisCell.Locked = False
Else
thisCell.Locked = True
End If
Next thisCell
ActiveSheet.Protect Password:="password", Contents:=True
End Sub
In excel go to Format|Cells... then select Protection tab and ensure the Locked tick box is Unchecked for your destination range of cells. Then use the Tools|Protection|Protect Sheet... to protect the sheet and any unlocked cells will be locked against alteration when the worksheet change.
Code:
This is a worksheet event code, which means that it needs to be placed in the appropriate worksheet code module, not a standard code module.
Option Explicit
Public Sub Worksheet_Change(ByVal Target As Range)
Call ApplyProtection(Range("A1:B20"))
Sheets("Sheet1").Protect Password:="password", UserInterfaceOnly:=True
End Sub
Private Sub ApplyProtection(thisRange As Range)
Dim thisCell As Range
ActiveSheet.Unprotect Password:="password"
For Each thisCell In thisRange
If IsEmpty(thisCell) Then
thisCell.Locked = False
Else
thisCell.Locked = True
End If
Next thisCell
ActiveSheet.Protect Password:="password", Contents:=True
End Sub
No comments:
Post a Comment