View Single Post
  #4   Report Post  
Posted to microsoft.public.excel.misc
JLatham JLatham is offline
external usenet poster
 
Posts: 3,365
Default Locking/Unlocking cells upon condition

You say "sheet code" - so I am presuming you want this to work automatically
and detect when add.years.1 goes = 3

Then in the sheet's code you need to use the _Calculate() event processor to
do this for you most likely, and I am also presuming you may want to toggle
the .Locked state of those cells, so here's what code to work that way could
look like:

Private Sub Worksheet_Calculate()
ActiveSheet.Unprotect
If Range("add.years.1").Value < 3 Then
ActiveSheet.Range("add.prv.yrs.1").Locked = False
ActiveSheet.Range("add.prv.yrs.2").Locked = False
Else
'= 3 processing
ActiveSheet.Range("add.prv.yrs.1").Locked = True
ActiveSheet.Range("add.prv.yrs.2").Locked = True
End If
ActiveSheet.Protect
End Sub

If your worksheet is protected with a password, then you'll need to provide
the password in the code, similiar to this:

Private Sub Worksheet_Calculate()
ActiveSheet.Unprotect Password:="mypassword"
If Range("add.years.1").Value < 3 Then
ActiveSheet.Range("add.prv.yrs.1").Locked = False
ActiveSheet.Range("add.prv.yrs.2").Locked = False
Else
'= 3 processing
ActiveSheet.Range("add.prv.yrs.1").Locked = True
ActiveSheet.Range("add.prv.yrs.2").Locked = True
End If
ActiveSheet.Protect Password:="mypassword"
End Sub

"Brettjg" wrote:

Hi JL, I've changed the code to this, but it still doesn't work. This is the
only code in the sheet code, nothing else at all. Am I missing some other
code that it needs? Currently the value of "add.years.1" is 1 so the cells
should be unlocked, but they are still locked.

Private Sub PERSONAL_LOCK()
If Range("add.years.1").Value = 3 Then
ActiveSheet.UNPROTECT
ActiveSheet.Range("add.prv.1").Locked = True
ActiveSheet.Range("add.prv.yrs.1").Locked = True
ActiveSheet.Range("add.prv.2").Locked = True
ActiveSheet.Range("add.prv.yrs.2").Locked = True
ActiveSheet.Protect
End If
End Sub


"JLatham" wrote:

Go back and create another named range that includes the cell(s) now referred
to as add.prv.1 and add.priv.yrs.2 and then revise your .Locked statement.

Lets say that add.prv.1 refers to A1 and add.priv.yrs.2 refers to B1. You
could select A1 and B1 and give them a name like add.priv.yrs.all then use
ActiveSheet.Range("add.priv.yrs.all").Locked = False

An alternative is to break the statement into two statements:
ActiveSheet.Range("add.priv.yrs.1").Locked = False
ActiveSheet.Range("add.priv.yrs.2").Locked = False




"Brettjg" wrote:

I have put the following code into the worksheet code but it doesn't work.
Can someone put me straight please?

Private Sub PERSONAL_LOCK()
If Range("add.years.1").Value < 3 Then
ActiveSheet.UNPROTECT
ActiveSheet.Range("add.prv.1:add.prv.yrs.2").Locke d = False
ActiveSheet.Protect
End If
End Sub

Thanks, Brett