简体   繁体   English

Excel VBA“堆栈空间不足”错误

[英]Excel VBA “out of stack space” error

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

Hi, I met a problem when trying to run the following piece of Excel VBA code. 嗨,我在尝试运行以下Excel VBA代码时遇到了问题。 A message box will pop out and say there is a 将弹出一个消息框,说有一个

"out of stack space" “堆栈空间”

problem to line Set rgn = range("f2:f200") , then another message box will pop out and say 问题到行Set rgn = range("f2:f200") ,然后会弹出另一个消息框并说出来

"method 'value' of object 'range' failed" “对象'范围'的方法'值'失败”

I don't know what is wrong... Thank you very much for helping. 我不知道出了什么问题......非常感谢你的帮助。

The problem is that you are changing cells in a Change event, which will trigger the event again, and again, and again... 问题是您正在更改事件中的单元格,这将再次触发事件,并再次,...

You need to disable events temporarily: 您需要暂时禁用事件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM