如何迭代动态增加的字典?似乎 excel VBA 预编译 For 循环的“限制”

PhD*_*PhD 2 excel vba

我的 VBA 代码中的 Scripting.Dictionary 对象正面临这个奇怪的问题。我希望继续遍历字典的总长度。我可能会在循环内向字典中添加更多项目,因此字典的大小可以动态变化,可以这么说。似乎它只迭代字典中最初的元素而不是新元素!

这是代码:

'Recursively continue to get all dependencies

    numberOfPreReqsToIterate = preReqGraph.Count - 1
    For preReqCount = 0 To numberOfPreReqsToIterate
        listOfPreReqs = preReqGraph.items
        rowNumberOfDependency = Application.WorksheetFunction.Match(listOfPreReqs(preReqCount), Range("requirementNumber"), 0)
        listOfPreReqsForCurrentPreReq = Application.WorksheetFunction.Index(Range("preReqList"), rowNumberOfDependency)

        If listOfPreReqsForCurrentPreReq <> "" Then
            preReqs = Split(listOfPreReqsForCurrentPreReq, ",")

            'Add each prereq to dictionary
            For i = 0 To UBound(preReqs)

                'If prereq already exists implies cycle in graph
                If preReqGraph.Exists(Trim(preReqs(i))) Then
                    MsgBox ("YOU HAVE A CYCLE IN PREREQUISTE SPECIFICATION!")
                    End
                End If

                'If not then add it to the preReqGraph. The value for the key is the key itself
                preReqGraph.Add Trim(preReqs(i)), Trim(preReqs(i))
                numberOfPreReqsToIterate = numberOfPreReqsToIterate + 1

            Next i
        End If
    Next preReqCount
Run Code Online (Sandbox Code Playgroud)

从概念上讲,我正在尝试获取依赖关系的整个“图”,并且如果确实如此,还可以检测到一个循环。我遍历单元格以找出此图并查看是否存在循环。我需要能够不断迭代字典中的所有项目,以获取尽可能多的项目。但似乎 excel 以某种方式“预编译”了 for 循环,因此仅采用原始上限/限制,但不采用新上限!我试过黑客攻击,这就是我所拥有的……但无济于事。

有任何想法吗?

附件是带有虚拟数据的 Excel 工作表示例……

在此处输入图片说明

对于 R4,preReqGraph 应该包含从 R8 到 R17 的所有内容。但是我得到的只是一个级别,即只有 R8 到 R12 和 R14 ......我很难过。我什至尝试过使用 preReqGraph.items 的 LBound 和 UBound 但无济于事。

Chr*_*ynn 5

最简单的方法是将 for 循环更改为 while 循环,然后手动增加索引变量。

Dim preReqCount as Integer
preReqCount = 0

While preReqCount <= numberOfPreReqsToIterate
    'Your Loop Logic

    preReqCount = preReqCount + 1
Wend
Run Code Online (Sandbox Code Playgroud)

  • 用户 Fink 对为什么 [这里] 有一些见解(http://stackoverflow.com/questions/3112751/why-doesnt-this-for-loop-process-the-full-data-set/3114247#3114247) (2认同)