2

I would not like this code to execute when the cell is empty. This code adds Now when I try to delete the contents of the cell.

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    If Target.Column = 1 Then
        Range("E" & Target.Row) = Now()
    End If
End Sub
Community
  • 1
  • 1
Horby
  • 45
  • 6

2 Answers2

3

Is this what you are trying?

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo Whoa

    If Target.Cells.CountLarge > 1 Then Exit Sub

    Application.EnableEvents = False

    If Not Intersect(Target, Columns(1)) Is Nothing Then
        If Target.Value <> "" Then Target.Offset(, 4).Value = Now
    End If

Letscontinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume Letscontinue
End Sub

More explanation about Worksheet_Change can be found HERE

Edit:

I tried test did not work! Date did not show do not know where wrong! – Horby 6 hours ago

The above code is for one worksheet and should be pasted in the relevant sheet code area. If you want to make it work for all worksheets then use the below code and paste it in the ThisWorkbook code area

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    On Error GoTo Whoa

    If Target.Cells.CountLarge > 1 Then Exit Sub

    Application.EnableEvents = False

    If Not Intersect(Target, Columns(1)) Is Nothing Then
        If Target.Value <> "" Then Target.Offset(, 4).Value = Now
    End If

Letscontinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume Letscontinue
End Sub
Community
  • 1
  • 1
Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250
0

To prevent your code from executing when the Target is empty, just make this small alteration:

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    If Target.Column = 1 And Target.Count = 1 Then
        If Len(Target) Then 
            Application.EnableEvents = False
            Range("E" & Target.Row) = Now()
            Application.EnableEvents = True
        End If
    End If
End Sub
Excel Hero
  • 14,253
  • 4
  • 33
  • 40