2

I've added VBA code which will insert either the time or date to a cell upon double clicking. I managed to get that going pretty well.

The bit I'm struggling with is getting the cell to protect and lock after the time/date has been entered.

I've got to a point where when I double click/try to edit a non-empty cell, I get a runtime error. Upon debugging, the line that throws me up is "Target.Formula = Format(Now, "ttttt")".

I'm also not able to throw an error message either.

I'm so close!

Any advice would be truly appreciated!

My code:

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


    If Not Intersect(Target, Range("C:E")) Is Nothing Then
        Cancel = True
        Target.Formula = Format(Now, "ttttt")
      End If

    If Not Intersect(Target, Range("A:A")) Is Nothing Then
        Cancel = True
        Target.Formula = Format(Now, "dd/mm/yyyy")

      End If


End Sub


Private Sub Worksheet_Change(ByVal Target As Range)

   On Error GoTo ErrorHandler

    Dim xRg As Range
    Set xRg = Intersect(Range("A:A,C:E"), Target)
    If xRg Is Nothing Then Exit Sub
    Target.Worksheet.Unprotect Password:="123"
    xRg.Locked = True
    Target.Worksheet.Protect Password:="123"

   Exit Sub
ErrorHandler:
   MsgBox "Cell already filled"

   Resume Next


End Sub
4

2 回答 2

2

使用 UserInterfaceOnly:=True 参数保护您的工作表一次,您无需取消保护/保护即可使用 VBA 更改单元格内容。

sub protectOnce()
    worksheets("sheet1").unprotect password:="123"
    worksheets("sheet1").protect password:="123", UserInterfaceOnly:=True
end sub
于 2018-02-12T13:54:07.523 回答
1

您的错误的原因是工作表被锁定,直到工作表上发生一些更改,所以如果您删除Worksheet_Change事件并让您的代码如下,那么它应该可以工作:

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
于 2018-02-12T13:44:59.503 回答