首页 > 解决方案 > VBA:如何编辑代码以消除堆栈空间不足的错误?

问题描述

这段代码曾经可以工作,但最近我收到一个错误(堆栈空间不足)。

我认为代码失败是因为我在没有退出/结束的情况下调用了太多次函数。

如果是这种情况,你可以调用一个函数多少次,我能做些什么来解决这个问题?

我不是这段代码的原作者。

我包括了发生错误的子。

    Sub CalculatePct(e As Variant)
        Dim G As Integer
        Dim pct As Double
        Dim Owned100Pct As Boolean
        If entities(e) < 0 Then

            pct = 0
            Owned100Pct = True  ' Keeps track if the entity exists in the table other than as a parent

            For G = 1 To UBound(MainArray, 1)
                If MainArray(G, colEntity) = e Then

                    Owned100Pct = False

                    If entities(MainArray(G, colParent)) = -1 Then
                        'If we don't know the parent's ownership percentage, go and calculate it
                        CalculatePct MainArray(G, colParent)    
                    End If

                    pct = pct + CDbl(MainArray(G, colPct)) / 100 * entities(MainArray(G, colParent))

                End If
            Next

            If Owned100Pct Then
                'Assume 100% owned if we don't know the parentage
                '("Outside" entities won't go through here as they are already set to 0%)
                entities(e) = 1
            Else
                'Store the entity's percentage
                entities(e) = pct
            End If
        End If

    End Sub

标签: excelvba

解决方案


您没有说明错误发生在哪一行,也没有说明 MainArray 代表什么,但我猜 MainArray 已经增长到大于可以使用有符号短整数访问的大小。

将迭代变量的声明更改为有符号长整数。这将变量的功能限制从 32,767 次迭代提高到 2,147,483,647 次。

Dim G As Long

推荐阅读