数据输入后锁定单元格

时间:2015-02-24 06:20:25

标签: vba excel-vba timestamp excel

我需要在给定范围内输入数据后锁定每个单元格。就像我输入Y或N一样,没有人可以再次编辑它。以下是我的代码,任何帮助将非常感谢。谢谢!

Private Sub Worksheet_Change(ByVal Target As Range)
Dim A As Range, MyPass As String, sh As Worksheet
Dim unit As Range
Set A = Range("E10:E22")
MyPass = "a"
Set sh = ActiveSheet
If Intersect(Target, A) Is Nothing Then Exit Sub
Set unit = Union(Target, Target.Offset(0, 1), Target.Offset(0, 2), Target.Offset(0, 3))
Application.EnableEvents = False
sh.Unprotect (MyPass)
unit.Locked = False
Target.Offset(0, 1) = Environ("Username")
Target.Offset(0, 2) = Now()
Target.Offset(0, 3) = Now()
unit.Locked = True
sh.protect (MyPass)
Application.EnableEvents = True
End Sub

1 个答案:

答案 0 :(得分:0)

我删除了一些变量,因为直接引用就是所需要的,而且您创建的 Set 范围从未设置为空。假设工作表当前受E10:E22解锁保护,则以下内容应按您的预期方式工作。

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Count > 1 Then Exit Sub
    If Not Intersect(Target, Range("E10:E22")) Is Nothing Then
        On Error GoTo Safe_Exit
        Application.EnableEvents = False
        Dim MyPass As String: MyPass = "a"
        Me.Unprotect MyPass
        'Target.Resize(1, 4).Locked = False  ' ◄ not needed when the sheet is unprotected
        Target.Offset(0, 1).Resize(1, 3) = Array(Environ("Username"), Now(), Now())
        Target.Resize(1, 4).Locked = True
        Me.Protect MyPass
    End If
Safe_Exit:
    Application.EnableEvents = True
End Sub