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

我在我的VBA代码中面对Scripting.Dictionary对象这个奇怪的问题。 我希望继续遍历字典的总长度。 我可以在循环中向字典添加更多的项目,所以字典的大小会dynamic变化。 它似乎只是迭代原来在字典中的许多元素,而不是新的!

代码如下:

'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 

从概念上讲,我试图获得整个依赖关系的“graphics”,并且在所有情况下也检测到一个循环。 我遍历单元格来找出这个图表,看看是否存在循环。 我需要能够继续遍历字典中的所有项目,以存在多个项目。 但似乎excel以某种方式“预编译”for循环,所以只有原始的上限/限制被采取,但不是新的! 我尝试了黑客入侵,这是我有…但无济于事。

有任何想法吗?

附件是带有虚拟数据的Excel工作表样本…

在这里输入图像说明

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

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

 Dim preReqCount as Integer preReqCount = 0 While preReqCount <= numberOfPreReqsToIterate 'Your Loop Logic preReqCount = preReqCount + 1 Wend