How to end infinite “change” loop in VBA

前端 未结 3 1032
名媛妹妹
名媛妹妹 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: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.

提交回复
热议问题