VBA: global variable cleared after section "Workbook_Open"

I have created an application level event class to monitor when creating / opening new books, following the CPearson guide . This works great in isolation. However, it is intended as part of an add-on. I am writing where a few more sub-sites are also called in the "Workbook_Open" section, see below code:

Private XLApp As baseCXlEvents

Private Sub Workbook_Open()
    Set XLApp = New baseCXlEvents
    test
    AddLocalReferences
    AddModules
    AddClassModules
    Debug.Print "testing"
End Sub

      

Thus, the variable XLApp

is called in the module scope as a class baseCXlEvents

. I added an event Class_Terminate

for this class and this is triggered after startup Debug.print "testing"

i.e. XLApp

ends after the subroutine has Workbook_Open

started. This does not happen when I quote sub AddLocalReferences

, AddModules

u AddClassModules

, who do exactly as their names suggested. Sub test

prints only messages in debug state to check if the call to additional subnets caused by XLApp

.

My current "guess" is that adding links, modules, or class modules counts as "editing", causing it to stop, as described in this MS Support . But if so, why XLApp

doesn't the end end of the sub? As opposed to how it is done AddLocalReferences

.

Any suggestions why the class is being terminated? I need to "stay alive" as well as load additional modules and addin links to workbook_open. Additional information about this code can be provided if needed.

I decided to add my baseCXlEvents class module code :

Option Explicit

Private WithEvents App As Application

Private Sub App_NewWorkbook(ByVal Wb As Workbook)
    MsgBox "New Workbook: " & Wb.Name
End Sub

Private Sub App_WorkbookOpen(ByVal Wb As Workbook)
    MsgBox "Workbook opened: " & Wb.Name
End Sub

Private Sub Class_Initialize()
    Debug.Print "Initializing baseCXlEvents instance.."
    Set App = Application
End Sub

Private Sub Class_Terminate()
    Debug.Print "Terminating baseCXlEvents instance.."
End Sub

      

+3


source to share


1 answer


Then try to strip the event handler stuff Workbook_Open

(where you add references, etc.) from class instantiation baseCXlEvents

with Auto_Open

.

First executed

Workbook_Open

is then executed Auto_Open

.

Note: baseCXlEvents

The Instancing parameter must be set to Public.

enter image description here



ThisWorkbook Class

Public XLApp As baseCXlEvents

Private Sub Workbook_Open()

    Test
    AddLocalReferences
    AddModules
    AddClassModules

End Sub

      

Standard module

Sub Auto_Open()
   Set ThisWorkbook.XLApp = New baseCXlEvents
End Sub

      

0


source







All Articles