Worksheet Change Event Stuck in Infinite Loop

此生再无相见时 提交于 2020-06-01 07:32:09

问题


I want the following code to do the following:

  • after I enter a value into a specific column, calculate some stuff and assign cell values with those calculated values

Problem:

  • the Worksheet.Change event will fire again after I assign a value to another cell, which restarts the sub and causes an infinite loop

How do I change my code such that it doesn't get stuck in an infinite loop and the cells I want to be updated will automatically update whenever I add a value to the column I'm working with?

Code - the column I'm adding values to is Column C:

Public Sub Worksheet_Change(ByVal Target As Range)
    Dim xlApp As Application
    Dim ws As Worksheet
    Dim r As Range
    Dim size As Long

    Set xlApp = Excel.Application
    Set ws = xlApp.ThisWorkbook.Worksheets("Sheet1")

    'get length of this individual column
    Set r = ws.Range(ws.Cells(2, 3), ws.Cells(ws.Rows.Count, 3).End(xlUp))
    'test to see if I got the correct column: i do
    r.Select
    size = r.Count

    With xlApp.WorksheetFunction
        'test to see if the offset I got was correct: it is
        r.Offset(0, 1).Select
        'get average of big range
        ws.Cells(3, 10).Value = .Average(r.Offset(0, 1)) ' <- here is where the change event will fire again
                                                         '    presumably because i just changed a value.
        'get standard deviation of big range's population
        ws.Cells(3, 11).Value = .StDev_P(r.Offset(0, 1))
        'test to see if the offset i got was correct: it is
        r.Offset(0, 2).Select
        ws.Cells(3, 12).Value = .Average(r.Offset(0, 2))
        ws.Cells(3, 13).Value = .StDev_P(r.Offset(0, 2))
    End With

    Set xlApp = Nothing
    Set ws = Nothing
    Set r = Nothing
End Sub

Thanks for reading!


回答1:


Disable Events before you make any changes on your sheet. Every change will [re]-activate the macro and round and round your system goes until your instance of excel crashes...

Application.EnableEvents = False
    'Changes go here
Application.EnableEvents = True


来源:https://stackoverflow.com/questions/51986899/worksheet-change-event-stuck-in-infinite-loop

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