2013-10-18 26 views
3

我有一个Worksheet_BeforeDoubleClick事件检查,看看广告点击一个细胞是否具有在一个Dictionary对象,像这样的数据:如何存储可用于多次事件调用的对象?

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 

但我遇到在测试过程中有很多这种问题,因为有很多的条件下,一个全局变量的值可以重置(如讨论here)。

我怎么能存储的对象,以便其价值将可只要工作簿是开放的,在整个重复调用我的BeforeDoubleClick事件?

+0

使你的代码稳定,这将是最好的保证,让你'公共variable'值。顺便说一句,为什么'全球'而不是'公共'? –

+1

存储它作为一个全球性的,但检查使用它,看它是否是'Nothing'之前:如果它不存在,然后使用'df.Create' –

回答

5
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 
+0

嗨重建它,你可能会想解释什么'dictFactory'是。一个类模块或其他东西? –

+0

这是从原来的问题 - 我没有介绍它。我认为这是OP创建的一个类。 –

0

这是真的,模块级变量(又名全局变量)的数据仍然存在,直到关闭工作簿,但代码不完全执行(因错误或故意中断)将重置变量,歼灭该数据。它发生在静态变量上,即使静态变量在本地范围内,它也像模块级变量一样工作。

为了安全起见,你可以在工作表模块中编写代码来检查,如果全局变量(引用字典)是有效的,如果不是,运行一个专门的程序来重新创建一个字典。

BTW,字典对象没有Create方法。

+0

对,我写了一个Create方法来收集数据集,然后填充该集的字典。 – sigil