PDA

View Full Version : Excel - lock range of cells in a row based on value in a cell



fotodj
08-26-2016, 01:29 PM
I have long drop down menus in cell A1, B1, C1 and I would like to protect the selections based on value in cell D1 which would have two drop down options "Lock" and "Open", what is the easiest way to do it?
Of course after switch back to value C1=Open row becomes editable again. This way each row would have a lock in cell D.

Kenneth Hobs
08-27-2016, 09:29 AM
Do you mean lock A1:C1 if D1=Lock and unlock those if D1=Open?

fotodj
08-28-2016, 03:45 AM
Kenneth , if I enter text "Lock" in cell D1 it should make cells A1:C1 uneditable, if I change value of the D1 to "Open" then I can edit range A1:C1 again

Kenneth Hobs
08-28-2016, 07:45 AM
Of course locking does no good if the sheet is not protected. The commented Protect line allows code to change the sheet.

Right click the sheet's tab, View > Code, and paste. Change ken to suit.

Private Sub Worksheet_Change(ByVal Target As Range)
With Target
If .Address <> "$D$1" Then Exit Sub
'Sheet1.Protect "ken", UserInterfaceOnly:=True
If .Value2 = "Open" Then
Range("A1:C1").Locked = False
Else
Range("A1:C1").Locked = True
End If
End With
End Sub
I like to put Protect code into the ThisWorkbook object so code elsewhere does not. Of course if you do use passwords in code, be sure to protect your VBAProject.

Private Sub Workbook_Open() Sheet1.Protect "ken", UserInterfaceOnly:=True
'Worksheets("Sheet1").Protect "ken", UserInterfaceOnly:=True
End Sub

fotodj
08-28-2016, 06:42 PM
Great piece of coding! Thank you Ken.