创建时间戳VBA

时间:2014-05-16 23:33:50

标签: excel vba excel-vba

需要此宏的帮助:

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 2 Then
    Application.EnableEvents = False
    Cells(Target.Row, 3).Value = Date + Time
    Application.EnableEvents = True
End If
End Sub

Sub DeleteCells()
For Each Cell In Range("B3:B25")
    If IsBlank(Cell.Value) Then
        Cell.Offset(0, 1).Clear
    End If
Next
End Sub

此宏的目的是创建时间戳。第一个宏工作正常。如果填写了行B中的任何内容,则将在行C中创建时间戳。但是,删除单元格功能不起作用。我想要它,以便如果有人删除B行中的单元格,时间戳也将被删除。

1 个答案:

答案 0 :(得分:1)

试试这个:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng As Range, c As Range

    'anything in ColB?
    Set rng = Application.Intersect(Me.Columns(2), Target)
    If rng Is Nothing Then Exit Sub 'nothing to process...

    Application.EnableEvents = False
    'could be >1 cell, so loop over them...
    For Each c In rng.Cells
        'skip any cells with errors
        If c.Row>=3 And Not IsError(c.Value) Then '<<edit
            c.EntireRow.Cells(3).Value = _
                IIf(Len(c.Value) > 0, Now, "")
        End If
    Next c
    Application.EnableEvents = True

End Sub