根据另一个单元格中的数字锁定多个单元格



根据特定单元格中的数字,例如B1, B3中锁定的单元格的数量应该等于该数字。例如,如果B1是20,那么B3:B23应该被锁定。同样地,如果B1是1000,那么锁单元应该是B3:B1003。下面的代码已经启动,但不能使用range命令。代码有什么问题?(我使用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

谢谢

代码正确地锁定了单元格。不过,要使锁生效,您需要保护床单。

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

如果您不想设置密码,只需从Unprotect和Protect语句中删除该参数。

最新更新