工作表更改事件陷入无限循环

jcr*_*izk 1 excel vba

我希望以下代码执行以下操作:

  • 在特定列中输入值后,计算一些内容并使用这些计算值分配单元格值

问题:

  • 在我为另一个单元格分配一个值后,Worksheet.Change 事件将再次触发,这会重新启动子并导致无限循环

如何更改我的代码,使其不会陷入无限循环,并且每当我向正在处理的列添加值时,我想要更新的单元格都会自动更新?

代码 - 我要添加值的列是 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
Run Code Online (Sandbox Code Playgroud)

谢谢阅读!

urd*_*boy 6

Events在对工作表进行任何更改之前禁用。如果没有Events禁用,您对工作表所做的每一次更改都会[重新]激活宏,并且您的系统会一直运行,直到您的 excel 实例崩溃......

Application.EnableEvents = False
    'Changes go here
Application.EnableEvents = True
Run Code Online (Sandbox Code Playgroud)