简体   繁体   English

锁定/解锁单元格excel VBA

[英]Locking/Unlocking cells excel VBA

I have a code i am trying to apply. 我有一个我要申请的代码。 The Objective of the macro is that when the relevant cell is double clicked a time stamp is applied then cell is locked from editing. 宏的目标是当双击相关单元格时,将应用一个时间戳,然后单元格将无法编辑。 If cells need to be edited then a password needs to be applied. 如果需要编辑单元格,则需要应用密码。

The problem is that i am not able to get the locking of the cells and password to work. 问题是我无法锁定单元格和密码才能正常工作。

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

    Application.EnableEvents = False

    With Target
        If .Column = 4 Then
            Select Case .Row
                Case 20, 24, 25, 27, 28, 30, 31, 32, 33, 34, 35, 37, 38, 40, 42, 43, 44, 54, 55, 56, 58, 59, 61, 62, 63, 64, 65
                    .Value2 = "Prepared By" & "  " & Environ("Username")
                    .Value2 = .Value2 & "  " & Format(Now, "yyyy-MM-dd hh:mm:ss")
                    .Value2 = .Locked = True
                     .Value2 = ActiveSheet.Protect Password:="Test"
                    End Select
                  End If
    End With
End Sub

Does this do the job? 这样行吗? Not sure what you want to happen if someone wants to change a filled cell. 如果有人要更改已填充的单元格,则不确定要发生什么。 You could have a separate SelectionChange or Change event to handle that. 您可以有一个单独的SelectionChange或Change事件来处理它。

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

With Target
    If .Column = 4 Then
        Select Case .Row
            Case 20, 24, 25, 27, 28, 30 - 35, 37, 38, 40, 42 - 44, 54 - 56, 58, 59, 61 - 65
                ActiveSheet.Protect Password:="Test", userinterfaceonly:=True
                .Value2 = "Prepared By" & "  " & Environ("Username")
                .Value2 = .Value2 & "  " & Format(Now, "yyyy-MM-dd hh:mm:ss")
                .Locked = True
        End Select
    End If
End With

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM