我正在Excel VBA中创建几个需要使用3个词典的自定义函数。
这些词典一旦设置就不会更改。
现在,每个字典都在每个函数中创建。
我希望清理它,设置一次字典,然后在函数中引用它。
不幸的是,我似乎找不到有关此主题的任何文档。
答案 0 :(得分:6)
您正在寻找全局变量,这些变量是在程序的所有执行过程中都保留在内存中的变量。
实际上:
Dim myDictionary As Scripting.Dictionary '<-- on top of module, outside of any macro/function. This makes the variable LOCAL to the module (i.e. accessible all over the subs and functions of the module)
'Alternatively (one or the other)
Public myDictionary As Scripting.Dictionary '<-- the variable is GLOBAL to all the program.
Sub init() '<-- initialize your dictionary once
Set myDictionary = New Scripting.Dictionary
myDictionary.add "Apples", 50
myDictionary.add "Bananas", 40
End Sub
Function a() As Integer
...
a = myDictionary("Apples") '<-- use your dictionary when you want
...
End Function
您可以在init
事件中调用ThisWorkbook.Open
,这样一来,打开工作簿后,字典将遍历整个执行过程。
答案 1 :(得分:4)
类似这样的东西:
'declare some global variables to hold your dictionaries
Dim dict1 as object, dict2 as object, dict3 as object
'a sub to create and populate the dictionaries
sub InitDicts()
If dict1 is nothing then
'create and populate dicts 1-3
End if
end sub
'*** functions which use the dictionaries ***
Function ThisFunction()
InitDicts
'use dicts
end function
Function ThatFunction()
InitDicts
'use dicts
end function