是否可以在函数之外创建和设置 VBA 字典?

Is it possible to create, and set VBA Dictionaries outside of a Function(s)?

我正在 Excel VBA 中创建几个需要使用 3 个词典的自定义函数。

这些词典一旦设置就不会改变。

现在每个字典都是在每个函数中创建的。

我更愿意清理它,设置一次字典并在函数中引用它。

遗憾的是,我似乎找不到关于此主题的任何文档。

像这样:

'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

您正在寻找全局变量,这些变量是在程序的所有执行过程中都存在于内存中的变量。

实际上:

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

您可以在 ThisWorkbook.Open 事件中调用 init,这样一旦您的工作簿打开,您的字典就会在整个执行过程中运行。