I am new to macros and I right this macro to lock and unlock specific cells according to values from others:
Private Sub Worksheet_Change(ByVal Target As range)
If [$A1] = "Yes" Then
ActiveSheet.Unprotect ("")
[$E:$E].locked = True
[$F:$F].locked = True
[$N:$N].locked = True
[$O:$O].locked = True
[$P:$P].locked = True
[$X:$X].locked = True
[$Y:$Y].locked = True
[$Z:$Z].locked = True
[$AA:$AA].locked = True
[$AB:$AB].locked = True
[$AC:$AC].locked = True
ActiveSheet.Protect ("")
Else
ActiveSheet.Unprotect ("PASSWORD")
[$E:$E].locked = False
[$F:$F].locked = False
[$N:$N].locked = False
[$O:$O].locked = False
[$P:$P].locked = False
[$X:$X].locked = False
[$Y:$Y].locked = False
[$Z:$Z].locked = False
[$AA:$AA].locked = False
[$AB:$AB].locked = False
[$AC:$AC].locked = False
ActiveSheet.Protect ("")
End If
If [$A1] = "No" Then
ActiveSheet.Unprotect ("")
[$B:$B].locked = True
ActiveSheet.Protect ("")
Else
ActiveSheet.Unprotect ("")
[$B:$B].locked = False
ActiveSheet.Protect ("")
End If
End Sub
By $A1
I mean to run the macro on all cells in column A and lock range of columns.
I don't know how to run and test and see if there any errors.
EDIT: i tried this and still can't test it or see how to work with it
Private Sub Worksheet_Change(ByVal Target As range)
If range("A1") = "Yes" Then
range("B1:B4").locked = True
ElseIf range("A1") = "No" Then
range("B1:B4").locked = False
End If
End Sub
Firstly the routine only makes sense if the cell that has changed is A1 - we should ignore this for any other cell.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$A$1" Then
Dim LockCells As Boolean
LockCells = (UCase(ActiveSheet.Range("A1")) = "YES")
Dim ColsToLock
ColsToLock = Split("E,F,N,O,P,X,Y,Z,AA,AB,AC", ",")
Dim r As Range
Dim x As Integer
ActiveSheet.Unprotect ""
For x = 0 To UBound(ColsToLock) - 1
Set r = ActiveSheet.Columns(ColsToLock(x) & ":" & ColsToLock(x))
r.Locked = LockCells
Next x
ActiveSheet.Protect ""
End If
End Sub
Secondly don't forget to unprotect all cells before you start
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.