Protect non-empty cells VBA

删除回忆录丶 提交于 2019-11-29 16:06:53

The reason for your error is that the sheet is locked until some change happens on the worksheet, so if you remove the Worksheet_Change event and have your code as follows then it should work:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Target.Worksheet.Unprotect Password:="123"
    If Not Intersect(Target, Range("C:E")) Is Nothing Then
        If Target.Value = "" Then
            Cancel = True
            Target.Formula = Format(Now(), "ttttt")
        End If
      End If

    If Not Intersect(Target, Range("A:A")) Is Nothing Then
        If Target.Value = "" Then
            Cancel = True
            Target.Formula = Format(Now, "dd/mm/yyyy")
        End If
    End If
Target.Worksheet.Protect Password:="123"
End Sub

Protect your worksheet once with the UserInterfaceOnly:=True parameter and you won't have to unprotect/protect to alter cell contents with VBA.

sub protectOnce()
    worksheets("sheet1").unprotect password:="123"
    worksheets("sheet1").protect password:="123", UserInterfaceOnly:=True
end sub
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!