How to end infinite “change” loop in VBA

前端 未结 3 1033
名媛妹妹
名媛妹妹 2020-12-20 17:57

I have a problem with visual basic. I want to make a macro/function that will multiply a number I enter by 3 and give a result in the same cell. I tried something like this:

相关标签:
3条回答
  • 2020-12-20 18:21

    With error handling to ensure .EnableEvents goes back to True:

    Sub Worksheet_Change(ByVal Target As Range)
        On Error GoTo CleanExit
        If Target.Address = "$Q$21" Then
            Application.EnableEvents = False
            Target.Value = Target.Value * 3
        End If
    CleanExit:
        Application.EnableEvents = True
        On Error GoTo 0
    End Sub
    
    0 讨论(0)
  • 2020-12-20 18:22

    When a Worksheet_Change event macro changes a value, you need to set Application.EnableEvents to false or risk triggering another event and having the macro run on top of itself.

    Sub Worksheet_Change(ByVal Target As Range)
        If Target.Address = "$Q$21" Then
            Application.EnableEvents = False
            Target.Value = Target.Value * 3
            Application.EnableEvents = True
        End If
    End Sub
    

    While I would usually involve some error control in order that the .EnableEvents was always reset to true, the above should get you started.

    0 讨论(0)
  • 2020-12-20 18:28

    You need to disable events to prevent recursion:

    Sub Worksheet_Change(ByVal Target As Range)
        If Target.Address = "$Q$21" Then
            application.enableevents = false
            Target.Value = Target.Value * 3
            application.enableevents = true
        End If
    End Sub
    

    Just as an alternative, you can also use your own variable rather than tinkering with EnableEvents, though it will mean your code responds twice even though it doesn't actually do anything the second time round:

    Dim bSkipEvents as Boolean
        Sub Worksheet_Change(ByVal Target As Range)
            If bSkipEvents then exit sub
            If Target.Address = "$Q$21" Then
                bSkipEvents = True
                Target.Value = Target.Value * 3
                bSkipEvents = False
            End If
        End Sub
    

    This is also the sort of approach you need with userforms and most events for activex controls on worksheets.

    0 讨论(0)
提交回复
热议问题