如何将vrnHistory字典声明为全局资源以实现跨过程调用?
如何在VBA中将Dictionary声明为全局资源?
要让vrnHistory字典能在多个过程(Sub/Function)间共享,你需要将它的声明移到所有过程外部,声明为模块级全局变量,具体步骤如下:
方案1:后期绑定(无需引用库)
在VBA模块的最顶部(所有Sub/Function代码之前)添加全局变量声明:
Public vrnHistory As Object
修改后的完整代码:
Public vrnHistory As Object Public Sub GlobalTest() Set vrnHistory = CreateObject("Scripting.Dictionary") vrnHistory.Add "A1", "This is dictionary Data for global share" FN_GlobalTest End Sub Public Function FN_GlobalTest() MsgBox "Within Function called from SUB " & vrnHistory("A1") End Function
方案2:早期绑定(需引用库,支持智能提示)
- 打开VBA编辑器,点击菜单栏的工具 > 引用,勾选「Microsoft Scripting Runtime」后确定。
- 在模块顶部声明全局变量:
Public vrnHistory As Scripting.Dictionary
修改后的完整代码:
Public vrnHistory As Scripting.Dictionary Public Sub GlobalTest() Set vrnHistory = New Scripting.Dictionary vrnHistory.Add "A1", "This is dictionary Data for global share" FN_GlobalTest End Sub Public Function FN_GlobalTest() MsgBox "Within Function called from SUB " & vrnHistory("A1") End Function
原代码问题说明
你原来的代码中,vrnHistory是在GlobalTest过程内部声明的局部变量,作用域仅局限于该过程,因此FN_GlobalTest无法访问到它。将变量声明移到模块级并使用Public关键字,就能让整个模块内的所有过程共享这个字典对象。
内容的提问来源于stack exchange,提问作者Mick
相关产品推荐
相关产品推荐

