Home » excel » excel – Lock certain cells depending on value from another cell

excel – Lock certain cells depending on value from another cell

Posted by: admin May 14, 2020 Leave a comment

Questions:

Im looking to lock a particular range of cells based on the input from a drop down in a row of data?

For example, In every row, third cell asks a question – “YES” or “NO” via a dropdown is given.If the user selects “NO”, then remaining three cells has to be locked. However, if the user selects, “Yes”, then the remainder of the cells shall remain available to enter data into.

   A         B          C            D         E         F  
| S.No   |  ID    |  Response   |  TIme  |  Value  | Expense | 
| 1      |  12345 |  NO         |  ----  |  ----   |  ----   |  (Locked Cells)
| 2      |  67y45 |  YES        |  44    |  1.68   |    1500 |  (UnLocked Cells)
| 3      |  12456 |  NO         |  ----  |  ----   |  ----   |  (Locked Cells)

like D2 to F2 has to be locked while D3 to F3 should be available for entry and again D4 to F4 is locked and so on,…

I tried the below code but it didn’t lock the cells or didn’t do any actions as far I observed

Private Sub Worksheet_Change(ByVal Target As Range)
    If Range("C2:C160") = "YES" Then
        Range("D2:D160").Locked = False
    ElseIf Range("C2:C160") = "NO" Then
        Range("D2:D160").Locked = True
        Range("E2:E160").Locked = True
        Range("F2:F160").Locked = True
    End If
End Sub

Took 160 as the highest range.

Any help would be really helpful, thanks.

How to&Answers:
Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    If Not Intersect(Target, Range("C2:C160")) Is Nothing Then Exit Sub
    If Target.Cells.Count > 1 Then Exit Sub

    Me.Unprotect Password:="password"

    If Target = "YES" Then            
        Target.Offset(0,1).Resize(1,3).Locked = False
    ElseIf Target = "NO" Then
        Target.Offset(0,1).Resize(1,3).Locked = True        
    End If

    Me.Protect Password:="password"

End Sub

The idea is to check the Target value. It is the cell, which is changed. Thus, you can start with Intersect(), which checks whether the changed cell is in Range("C2:C160"):

If Not Intersect(Target, Range("C2:C160")) Then Exit Sub

Then try to see whether the changed cells are more than 1:

If Target.Cells.Count > 1 Then Exit Sub

At the end, based on the "YES" and “NO” you can give lock cells. You may consider using UCase(), in order to make your code work for “yes” as well”

If UCase(Target) = "YES" Then
...
ElseIf UCase(Target) = "NO" Then

Concerning locked and unlocked cells and whether you can select them, see this article, the properties are explained quite well:

https://support.office.com/en-us/article/lock-or-unlock-specific-areas-of-a-protected-worksheet-75481b72-db8a-4267-8c43-042a5f2cd93a