如何存储可在许多事件调用中使用的对象



我有一个Worksheet_BeforeDoubleClick事件,用于检查单击的单元格是否具有字典对象中的数据,如下所示:

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

但是我在测试过程中遇到了很多问题,因为在很多条件下可以重置全局变量的值(如此处所述)。

如何存储对象,以便在工作簿处于打开状态时,在对 BeforeDoubleClick 事件的重复调用中,其值将可用?

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

确实,模块级变量(也称为全局变量)的数据会一直保留到工作簿关闭,但代码的不完整执行(由于错误或故意中断)将重置变量,从而清除该数据。 它也发生在静态变量上,即使静态变量在范围内是局部的,它们在持续时间方面的工作方式也类似于模块级变量。

为了安全起见,您可以在工作表模块中编写代码来检查全局变量(引用字典)是否有效,如果无效,请运行专用过程以重新创建字典。

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

最新更新