
object created in workbook_open event handler disappears on exit from the event handler
Hello Toby,
I believe I know the problem. I can reproduce the problem using this code:
Contents of ThisWorkbook Module:
------------------------
Option Explicit
Private obj As Object
Private Sub Workbook_Open()
ThisWorkbook.VBProject.References.AddFromGuid
"{00020905-0000-0000-C000-000000000046}", 0, 0
Set obj = CreateObject("Word.Application")
obj.Visible = True
TestObj
End Sub
Public Sub TestObj()
MsgBox "TypeName of obj: " & TypeName(obj)
End Sub
------------------------
I open the workbook and the Open event automates Word and calls TestObj to
display the typename of the variable, which is "Application". But, when I
run the Thisworkbook.TestObj procedure again, it displays "Nothing."
The problem is caused by adding a reference to the VBA project
programmatically. If you remove that line, the problem does not occur.
But by adding a reference, this forces the VBA project to "reset" itself.
The same happens if you programmatically add a procedure to the project.
The project resets because it needs to recompile. This causes any public
variables to reset and is considered by design.
I'm not sure of the best way to code around this. One idea is to use a
ontime macro. For example, I could replace the above scenario with the
following and it works around the problem:
Option Explicit
Private obj As Object
Private Sub Workbook_Open()
ThisWorkbook.VBProject.References.AddFromGuid
"{00020905-0000-0000-C000-000000000046}", 0, 0
'Now, end this sub and enable a new sub to run the remainder of the
code:
Application.OnTime Now + TimeValue("00:00:01"), _
ThisWorkbook.Name & "!ThisWorkbook.Workbook_OpenContinue"
End Sub
Private Sub Workbook_OpenContinue()
Set obj = CreateObject("Word.Application")
obj.Visible = True
TestObj
End Sub
Public Sub TestObj()
MsgBox "TypeName of obj: " & TypeName(obj)
End Sub
HTH,
Greg Ellison
Microsoft Developer Support