2013 Excel VBA在删除另一个单元格时删除单元格的内容

时间:2015-11-30 17:15:03

标签: vba

下面是我在第1列中输入数字时用来自动填充第3列中日期的vba代码。我需要在删除第1列中的数字时删除日期。

    Private Sub Worksheet_Change(ByVal Target As Range)

    Dim A As Range, B As Range, Inte As Range, r As Range
    Set A = Range("A:A")
    Set Inte = Intersect(A, Target)
    If Inte Is Nothing Then Exit Sub
    Application.EnableEvents = False
    For Each r In Inte
    r.Offset(0, 2).Value = Date
    Next r
    Application.EnableEvents = True
    End Sub

1 个答案:

答案 0 :(得分:1)

它遇到了问题,因为第3列的删除触发了另一个更改状态,因此我只是在顶部说一些内容,如果更改不在第1列,那么不要担心它。这应该有效:

Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Column = 1 Then
        Dim A As Range, B As Range, Inte As Range, r As Range
        Set A = Range("A:A")
        Set Inte = Intersect(A, Target)
        'If Inte Is Nothing Then Target.Offset(0, 3 - Target.Column).Value = "YES"
        If Target.Offset(0, 1 - Target.Column).Value = "" Then
            Target.Offset(0, 3 - Target.Column).Clear
            Exit Sub
        End If
        'If Inte Is Nothing Then Exit Sub
        Application.EnableEvents = False
        For Each r In Inte
        r.Offset(0, 2).Value = Date
        Next r
        Application.EnableEvents = True
    End If

End Sub