How to change cell value using Worksheet_change event without triggering a second call

夙愿已清 提交于 2020-06-12 08:17:00

问题


I'm working on a simple worksheet, and I need to change some data in the cells depending on the user input; those changes are made using the Worksheet_Change event. However, when I change another cell, the event is triggered again, so it becomes quite a headache (it's kind of a "chicken-and-egg" scenario).

Example:

private sub Worksheet_Change(ByVal Target as Range)
    with target ' Only cells in column C are unlocked and available for edition
        select case .row
            case 4
                if .value = 1 then
                    ActiveSheet.cells(5,3).value = 0
                else
                    ActiveSheet.cells(5,3).value = 1
                end if
            case 5
                if .value = 1 then
                    ActiveSheet.cells(4,3).value = 0
                else
                    ActiveSheet.cells(4,3) = 1
                end
       end select
    end with
end sub

As you can see, changes in row 4 trigger changes in row 5, which may trigger another change in row 4... and it becomes an "infinite call", which eventually crashes excel.

So, the question is: Is there a way to programmatically change the value of a cell without triggering the Worksheet_Change event?


回答1:


Disable interrupts while changing cells, then re-enable them when you are done:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim A As Range
    Set A = Range("A1")
    If Intersect(Target, A) Is Nothing Then Exit Sub
    Application.EnableEvents = False
        A.Value = ""
        A.Offset(0, 1).Value = "CLEARED"
    Application.EnableEvents = True
End Sub


来源:https://stackoverflow.com/questions/28220333/how-to-change-cell-value-using-worksheet-change-event-without-triggering-a-secon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!