仅在手动更改时为不同的单元格运行不同的宏

时间:2015-11-25 18:31:42

标签: excel vba excel-vba events event-handling

我的问题是我写的宏改变了细胞的值,再次触发一个宏来改变其他一个细胞。

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim cell As Range
    For Each cell In Target
        If Not Intersect(cell, Range("c2")) Is Nothing Then
            Macro1
        ElseIf Not Intersect(cell, Range("C3")) Is Nothing Then
            Macro2
        ElseIf Not Intersect(cell, Range("d8")) Is Nothing Then
            Macro3
        End If
    Next cell
End Sub

运行的宏总是会改变其他单元格,这就是目前无限循环的原因。

有没有办法只让手动输入/更改单元格让宏运行?

1 个答案:

答案 0 :(得分:2)

两种解决方案:

  1. 在_change事件开始时添加Application.EnableEvents = False,并在结尾处将其设置为True
  2. 创建一个公共布尔值来测试您是否已经自动进行任何更新
  3. 像这样(解决方案2):

    Public DisableEvents As Boolean
    
    Private Sub Worksheet_Change(ByVal Target As Range)
    If DisableEvents Then Exit Sub
        DisableEvents = True
    
        Dim cell As Range
        For Each cell In Target
            If Not Intersect(cell, Range("c2")) Is Nothing Then
                Macro1
            ElseIf Not Intersect(cell, Range("C3")) Is Nothing Then
                Macro2
            ElseIf Not Intersect(cell, Range("d8")) Is Nothing Then
                Macro3
            End If
        Next cell
    
        DisableEvents = False
    End Sub
    
    
    Sub Macro1()
    If DisableEvents Then Exit Sub
    
    'Rest of your code
    
    End Sub