macros完成后,VBA保留实例(Excel)

我有我自己的一些对象,我在Excel中的ThisWorkbook里面实例化。 我有一些麻烦 ,我认为这个问题是macros一旦结束VBA就会杀死我的实例。

我们正在使用ThisWorkbook

  • 如果我在macros中为ThisWorkbook定义自己的variables,那么即使variables在ThisWorkbook的类中Dim'd而不在模块中,该variables的值也会在macros完成后回到初始化值。 (即0,Nothing等)

  • 如果我在Workbook_Open()事件中为ThisWorkbook实例化一个对象,则当事件完成时,该对象被销毁。 同样,即使variables在ThisWorkbook类中是Dim'd而不在Workbook_Open()的子类中,

有什么我可以做,以确保这些对象生存下来,这些variables保持其价值?

ThisWorkbook

 'Object we want to survive Dim myInstance As MyObject Private Sub Open_Workbook() Set myInstance = new MyObject ' Object is instantiated End Sub ' Macro 1 Public Sub MyMacro() Set myInstance = new MyObject ' Object is instantiated End Sub ' Macro 2 Public Sub CheckInstance() If Not myInstance is Nothing Then MsgBox "I found an instance!" End If End Sub 

既不打开工作簿也不运行macros1将导致macros2findmyInstance。 在这两种情况下,Macro2都会认为myInstance是Nothing。 如果Macro 2或Open_Workbook(在它们的End Sub之前)被调用,macros2将只能findmyInstance。 我需要修复这个。 (我从单独的窗体button运行这些macros,而不是在其他macros内。

是的,你需要在你的macros之外创buildvariables。

否则,它们将会随着macros观的结束而被破坏。

 'will be available as long the file is open Private lngTest as long Private Sub Worksheet_Change() 'will be available as long as routine is running Dim lngTest2 as long lngTest = lngTest + 1 lngTest2 = lngTest2 + 1 debug.print lngTest debug.print lngTest2 End Sub 

因为您正在讨论Workbook_Open – 要保存variables,即使通过closures并重新打开工作簿,您也需要另一个构造。 我的build议将他们存储在工作表,但我相信还有其他方法。

编辑:

用这个testing你的发布代码 – 工作正常,find实例。

MyObject作为一个类:

 Private lngTest As Long Public Property Get test() As Long test = lngTest End Property Public Property Let test(ByVal lngValue As Long) lngTest = lngValue End Property 

在VBA编辑器( Module1 )中为项目创build一个新模块,并插入以下代码:

 Dim testVar As Integer Sub Test() testVar = testVar + 1 MsgBox testVar End Sub 

然后添加一行,例如工作表的激活或打开事件:

 Module1.Test 

它对我来说很有效,每次激活工作表时,价值都在递增。

为什么不试图使用数组? 你把它从你的macros中调出来,它将保存数据,直到你用另一个macros清除它或者closures工作簿。