2

希望这个问题还没有被问到,我尝试寻找答案但找不到任何东西。

这可能是一个简单的问题,但我正在用 excel 编写我的第一个宏,并且遇到了一个我找不到解决方案的问题。我编写了几个宏,它们基本上根据同一行的另一列中的值动态汇总列(以便行数可以更改并且公式自动向下移动),我从 event 中调用这些宏Workbook_SheetChange

我遇到的问题是,我从宏中更改单元格的值以显示总和的结果,然后Workbook_SheetChange再次调用,这是我不想要的。现在它可以工作,但我可以追踪它并看到它Workbook_SheetChange被多次调用。这阻止了我向宏添加其他单元格更改,因为这样会导致无限循环。

我希望每次对工作表进行更改时都运行宏,但我看不到任何允许宏更改单元格值的方法,所以我不知道该怎么做。我将在下面粘贴我的代码,以防万一。

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    Dim Row As Long
    Dim Col As Long
    Row = Target.Row
    Col = Target.Column
    If Col <> 7 Then
        Range("G" & Row).Select
        Selection.Formula = "=IF(F" & Row & "=""Win"",E" & Row & ",IF(F" & Row & "=""Loss"",-D" & Row & ",0))"
        Target.Select
    End If
    Call SumRiskColumn
End Sub

Private Sub Workbook_SheetCalculate(ByVal Sh As Object)
    Call SumOutcomeColumn
End Sub

Sub SumOutcomeColumn()
    Dim N As Long
    N = Cells(Rows.Count, "A").End(xlUp).Row
    Cells(N + 1, "G").Formula = "=SUM(G2:G" & N & ")"
End Sub

Sub SumRiskColumn()
    Dim N As Long
    N = Cells(Rows.Count, "A").End(xlUp).Row
    Dim CurrTotalRisk As Long
    CurrTotalRisk = 0
    For i = 2 To N
        If IsEmpty(ActiveSheet.Cells(i, 6)) And Not IsEmpty(ActiveSheet.Cells(i, 1)) And Not IsEmpty(ActiveSheet.Cells(i, 2)) And Not IsEmpty(ActiveSheet.Cells(i, 3)) Then
            CurrTotalRisk = CurrTotalRisk + ActiveSheet.Cells(i, 4).Value
        End If
    Next i
    Cells(N + 1, "D").Value = CurrTotalRisk
End Sub

谢谢你能给我的任何帮助!对此,我真的非常感激。

4

1 回答 1

5

用于Application.EnableEvents防止 Excel 调用事件过程。

放在 Application.ScreenUpdating = False代码的开头和Application.ScreenUpdating = True结尾。

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    Application.EnableEvents = False
    Dim Row As Long
    Dim Col As Long
    Row = Target.Row
    Col = Target.Column
    If Col <> 7 Then
        Range("G" & Row).Select
        Selection.Formula = "=IF(F" & Row & "=""Win"",E" & Row & ",IF(F" & Row & "=""Loss"",-D" & Row & ",0))"
        Target.Select
    End If
    Call SumRiskColumn
    Application.EnableEvents = True
End Sub

Private Sub Workbook_SheetCalculate(ByVal Sh As Object)
    Application.EnableEvents = False
    Call SumOutcomeColumn
     Application.EnableEvents = True
End Sub
于 2013-11-02T03:53:47.213 回答