Excel VBA"堆栈空间不足"错误

时间:2017-06-13 07:36:32

标签: excel-vba vba excel

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim b As Integer
    b = 0

    Dim cell As Range
    Dim rgn As Range

    Set rgn = Range("f2:f200")

    For Each cell In rgn
        If IsEmpty(cell) = False Then
            b = b + 1
        End If
    Next

    Range("d2").Value = b
End Sub

嗨,我在尝试运行以下Excel VBA代码时遇到了问题。将弹出一个消息框,说明有

  

"堆栈空间不足"

问题到行Set rgn = range("f2:f200"),然后弹出另一个消息框并说

  

"方法'价值'对象'范围'失败"

我不知道出了什么问题......非常感谢您的帮助。

1 个答案:

答案 0 :(得分:6)

问题是您正在更改Change事件中的单元格,这将再次触发事件,并再次触发......

您需要暂时禁用事件:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim b As Integer
    b = 0

    Dim cell As Range
    Dim rgn As Range

    Set rgn = Range("f2:f200")

    For Each cell In rgn
        If IsEmpty(cell) = False Then
            b = b + 1
        End If
    Next
    Application.Enableevents = False
    Range("d2").Value = b
    Application.Enableevents = True
End Sub