如何锁定数据验证单元并在双击时解锁

时间:2019-04-18 09:00:36

标签: excel vba

我可以锁定工作表中的所有单元格,并通过双击并输入密码来解锁它们以进行编辑。

我唯一的问题是该代码对于Data Validation单元根本不起作用。我无法双击和编辑数据验证值。

还有一种方法可以让我自动保护空白单元格,并在输入值后立即保护它,然后双击以请求密码来解锁该单元格,就像我使用的代码一样。

    Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel 
    As Boolean)
    If Target.Value <> "" Then
    changeInput = MsgBox("Do you want to unlock the sheet?", vbYesNo + 
    vbQuestion, "Unlock sheet")
    If changeInput = vbYes Then
        Dim pass As String
        pass = InputBox("Enter Password")
            If pass <> "password" Then
                MsgBox ("Wrong password")
            Else
                ActiveSheet.Unprotect Password:="password"
                Target.Locked = False
            End If
    End If
    End If
    End Sub

    Private Sub Worksheet_Change(ByVal Target As Range)
    Dim cel As Range
    ActiveSheet.Unprotect Password:="password"
    For Each cel In Target
    If cel.Value <> "" Then
        cel.Locked = True
    End If
    Next cel
    ActiveSheet.Protect Password:="password"

    End Sub

该代码适用于所有其他单元格,但我希望空白单元格是可编辑的,并且此代码不适用于数据验证单元格。

1 个答案:

答案 0 :(得分:0)

对于Data-Validation单元,请在worksheet_change事件中尝试:

library(lubridate)
df %>% 
mutate_at("Date",dmy) %>%  #convert to date-object
arrange(Date) %>%  #sort by date
group_by(ID,Value) %>%  #group by ID-Value pairs
mutate(Occurence = row_number()) #mutate new column with occurence

df
     ID Value Date       Occurence
  <int> <chr> <date>         <int>
1     2 a     1975-12-06         1
2     4 a     1991-01-01         1
3     3 a     2015-01-02         1
4     3 c     2015-03-01         1
5     2 b     2016-03-12         1
6     2 b     2017-04-05         2
7     1 b     2018-05-02         1
8     1 a     2019-01-01         1
9     1 a     2019-03-03         2

代替

ActiveSheet.Protect DrawingObjects:=False, Password:="password"

一种自动取消保护空白单元格的方法是确保所有空白单元格都不会被刮擦。