Domanda

Depending on the number in a particular cell, say B1, the number of locked cells from B3 should equal that number. For example if B1 was 20, than B3:B23 should be locked. Likewise if B1 was 1000, the lock cells should be B3:B1003. The code below was started although doesn't work with the range command. What is wrong with the code? (I'm using excel 2010)

Private Sub Worksheet_Change(ByVal Target As Range)
Dim tValue As Integer
If Target = Range("B1") Then
    If Not IsNumeric(Target.Value) Then
        MsgBox "Not a valid value"
    Else
        tValue = Target.Value + 2
        Range("B3" & tValue, "B1003").Locked = False
        Range("B3", "B" & tValue).Locked = True
    End If
End If
End Sub

Thank you

È stato utile?

Soluzione

The code locks the cells correctly. You need to protect the sheet for the lock to come into effect, though.

Private Sub Worksheet_Change(ByVal Target As Range)
Dim tValue As Integer
If Target = Range("B1") Then
    If Not IsNumeric(Target.Value) Then
        MsgBox "Not a valid value"
    Else
        ActiveSheet.Unprotect Password:="secret"
        tValue = Target.Value + 2
        Range("B3" & tValue, "B1003").Locked = False
        Range("B3", "B" & tValue).Locked = True
        ActiveSheet.Protect Password:="secret"
    End If
End If
End Sub

If you don't want to set a password, just remove the parameter from the Unprotect and Protect statements.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top