title: VBA: Global Variable Cleared after 'Workbook_Open' sub
body: <p>I have set up an application level event class to monitor when new workbooks are created/ opened by following <a href="http://www.cpearson.com/excel/appevent.aspx" rel="nofollow noreferrer">CPearson's guide</a>. This works fine in isolation. However, it is intended as part of add-in I'm writing where several other subs are also called in the 'Workbook_Open' sub, see below code:</p>
  
  <pre><code>Private XLApp As baseCXlEvents
  
  Private Sub Workbook_Open()
      Set XLApp = New baseCXlEvents
      test
      AddLocalReferences
      AddModules
      AddClassModules
      Debug.Print "testing"
  End Sub
  </code></pre>
  
  <p>So the <code>XLApp</code> variable is called in the module scope as a <code>baseCXlEvents</code> class. I have added a <code>Class_Terminate</code> event to this class and this is triggered after the <code>Debug.print "testing"</code> is run, i.e. <code>XLApp</code> is terminated after the <code>Workbook_Open</code> sub has run. This does not happen when I quote out the subs <code>AddLocalReferences</code>, <code>AddModules</code>, and <code>AddClassModules</code>, which do exactly as their names would imply. The sub <code>test</code> only prints a messages in debug to test whether calling additional subs caused <code>XLApp</code> to be terminated.</p>
  
  <p>My current 'hunch' is that adding references, modules, or class modules counts as "editing", causing it to be terminated, as explained in <a href="https://support.microsoft.com/en-gb/kb/141693" rel="nofollow noreferrer">this MS Support document</a>. But, if so, why doesn't <code>XLApp</code> get terminated until the end of the sub? As opposed to as soon as <code>AddLocalReferences</code> is run.</p>
  
  <p>Any suggestions why the class is terminated? I need it to 'stay alive' and also need to load additional modules and references for the addin upon workbook_open. If needed more details of this code can be provided.</p>
  
  <p>I've decided to add my <strong>baseCXlEvents class module's code</strong>:</p>
  
  <pre><code>Option Explicit
  
  Private WithEvents App As Application
  
  Private Sub App_NewWorkbook(ByVal Wb As Workbook)
      MsgBox "New Workbook: " &amp; Wb.Name
  End Sub
  
  Private Sub App_WorkbookOpen(ByVal Wb As Workbook)
      MsgBox "Workbook opened: " &amp; 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
  </code></pre>