我面临的问题是,我有一个对象/集合将在堆栈的底部创建,并且我的程序深度为3层,该集合将仅在3(top)层使用,第一个项目将被使用并从集合中删除,但是我想保留它在整个程序中使用,因为下一步需要使用集合中的下一个项目,直到完成整个过程为止。
我想做的最好方法是在最底层使用该集合创建该集合,即使该集合不在范围内也要保持该集合。
我现在的操作方式是在最底层创建集合并将其向下传递,因为如果我在顶层创建集合,它将在超出范围后被删除
我觉得必须有一种更好的方法来解决我的问题,但我找不到。有人知道答案吗?
我只是在excel中设置了一些文本,如下所示
(A)(1)
(B)(2)
(C)(3)
(D)(4)
(E)(5)
'The Code works, but what I am asking is it possible to dont pass dict through all those sub
Sub Main()
Static dict As New Dictionary
Dim x As Integer
Set dict = readrange
Do While x < 3
somesub dict
x = x + 1
Loop
End Sub
'-----------------------下一个模块--------------------- -------------------------------
Sub somesub(dict As Dictionary) '<----------------------- Dont want this dict
'some code which doesnt not use the dict
Dictchange dict
End Sub
'-----------------------下一个模块--------------------- -------------------------------
Sub Dictchange(dict As Dictionary) '<----------------------- Dont want this dict too
Cells(dict(dict.Keys(0)), 4) = "Done"
'Is it possible to call dict in Main without pass the chain
'I cant use public as in the real code, "somesub" and "Dictchange" are in different module
'I could use Global, but i always feel like it just a "Dirty" way to fix thing
dict.Remove dict.Keys(0)
End Sub
'-----------------------下一个模块--------------------- -------------------------------
'In the real code, this is one function in a class Module
Function readrange() As Dictionary
Dim temp As New Dictionary
For i = 1 To 5
temp.Add Cells(i, 1).Value, Cells(i, 2).Value
Next i
Set readrange = temp
End Function
我希望这会有所帮助
答案 0 :(得分:0)
正如我在评论中已经说过的:将dict
设置为全局变量。
Option Explicit
Public dict As Dictionary 'this is globally defined in a module
Sub Main()
Dim x As Long
Set dict = ReadRangeToDict
Do While x < 3
SomeProcedure
x = x + 1
Loop
End Sub
Function ReadRangeToDict() As Dictionary
Dim TempDict As New Dictionary
Dim iRow As Long
For iRow = 1 To 5
If Not TempDict.Exists(Cells(iRow, 1).Value) Then 'check if key already exists to prevent errors!
TempDict.Add Cells(iRow, 1).Value, Cells(iRow, 2).Value
End If
Next iRow
Set ReadRangeToDict = TempDict
End Function
因此,您可以通过任何其他过程/函数来访问它,而无需将其作为参数。
Sub SomeProcedure()
'output the dict in the immediate window
Dim itm As Variant
For Each itm In dict
Debug.Print itm, dict(itm)
Next itm
End Sub