更改Excel VBA目标单元格然后忽略

时间:2016-10-25 08:53:31

标签: excel vba excel-vba

我有一个宏来检测细胞何时被更改,并将此数字添加到其上方的单元格中。

然而,我需要清除原始单元格,它会再次触发宏,因为该单元格再次被更改,我最终会无限循环。有没有办法去"忽略"当宏运行时,任何其他单元格都会发生变化吗?

Private Sub Worksheet_Change(ByVal Target As Range)

Dim KeyCells As Range
Set KeyCells = Range("B3:O3")

If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then
    If Range(Target.Address).Cells.Count = 1 Then
        Range(Target.Address).Offset(-1).Value = Range(Target.Address).Offset(-1).Value + Range(Target.Address).Value
        Range(Target.Address).Clear
    End If
End If

End Sub

2 个答案:

答案 0 :(得分:1)

或者只需添加Application.EnableEvents,如下所示:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

Dim KeyCells As Range
Set KeyCells = Range("B3:O3")

If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then
    If Range(Target.Address).Cells.Count = 1 Then
        Application.EnableEvents = False
        Range(Target.Address).Offset(-1).Value = Range(Target.Address).Offset(-1).Value + Range(Target.Address).Value
        Range(Target.Address).Clear
        Application.EnableEvents = True
    End If
End If

End Sub

答案 1 :(得分:0)

您可以添加其他条件:

Private Sub Worksheet_Change(ByVal Target As Range)

Dim KeyCells As Range
Set KeyCells = Range("A3:O3")

If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing And Range(Target.Address).Value <> "" Then
    If Range(Target.Address).Cells.Count = 1 Then
        Range(Target.Address).Offset(-1).Value = Range(Target.Address).Offset(-1).Value + Range(Target.Address).Value
        Range(Target.Address).Clear
    End If
End If

End Sub