Vba 如何存储可用于许多事件调用的对象?

Vba 如何存储可用于许多事件调用的对象?,vba,excel,Vba,Excel,双击前我有一个工作表\u事件,检查单击的单元格是否包含字典对象中的数据,如下所示: Private Sub Worksheet_BeforeDoubleClick(ByVal Target as Range, Cancel as Boolean) Dim dict as Dictionary Dim df as New dictFactory 'returns a dictionary populated with all list items Set dict=df.create If

双击前我有一个
工作表\u
事件,检查单击的单元格是否包含字典对象中的数据,如下所示:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target as Range, Cancel as Boolean)

Dim dict as Dictionary
Dim df as New dictFactory

'returns a dictionary populated with all list items
Set dict=df.create

If dict.Exists(Target.Value) Then
 MsgBox "Exists"
Else
 MsgBox "Doesn't exist"
End If

End Sub
问题是,这需要在每次单击单元格时创建一个新词典。我认为最好将字典存储在自己模块中的全局变量中,如下所示:

Global valuesDict As New Dictionary
然后在打开工作簿时填充它:

Private Sub workbook_open()

Dim df as New dictFactory
Set valuesDict=df.create

End Sub
但是我在测试过程中遇到了很多问题,因为有很多条件可以重置全局变量的值(如所讨论的)


如何存储一个对象,使其值在工作簿打开时,在双击事件之前重复调用my
期间可用?

模块级变量(也称全局变量)的数据确实会一直存在,直到工作簿关闭,但代码执行不完全(由于错误或故意中断)将重置变量,清除数据。静态变量也会发生这种情况,即使静态变量在作用域中是局部变量,但在持续时间方面与模块级变量类似

Global valuesDict As Dictionary 'EDIT - drop the "new"

Private Sub Worksheet_BeforeDoubleClick(ByVal Target as Range, Cancel as Boolean)

'populate global only when needed
if valuesDict is Nothing then CreateDict

If dict.Exists(Target.Value) Then  MsgBox "Exists"
Else
 MsgBox "Doesn't exist"
End If

End Sub
'


Private Sub workbook_open()
    CreateDict
End Sub
'


Sub CreateDict()
    Dim df as New dictFactory
    Set valuesDict=df.create
End sub
为了安全起见,您可以在工作表模块中编写代码,检查全局变量(引用字典)是否有效,如果无效,请运行专用过程重新创建字典


顺便说一句,dictionary对象没有创建方法。

使您的代码稳定,这将是使您保持
公共变量
值的最佳保证。顺便说一句,为什么
全局
而不是
公共
?将其存储为全局,但在使用之前检查它是否为
:如果它不存在,请使用重新创建它de>df.Create
好的,我写了一个Create方法来收集数据集,然后从数据集中填充字典。嗨,你可能想解释什么是
dictFactory
。一个类模块还是其他什么?这是原始问题-我没有介绍它。我假设它是OP创建的一个类。