title: Wiring up interop event doubles Excel VBA macro execution time
body: <p>I have a problem where wiring up an event causes a vba macro to double in execution time even when the event doesn't get triggered.</p>
  
  <p>From C# interop I call a macro in an Excel workbook that calculates specialized rating information for an insurance policy. This workbook also calls another workbook to calculate some standard rating figures. I also wire up an event on workbook open so that if a user opens a separate (unrelated) spreadsheet it gets opened in a separate application instance. This all works fine.</p>
  
  <p>The users operate in a VDI environment. They are complaining because this process takes up to 30 seconds and they would like it to be quicker. On a physical machine it typically only takes 3-10 seconds depending on the policy.</p>
  
  <p>In testing I notice that if I don't wire up the workbook open event then the process is twice as quick (or more). As soon as I add the event back the macro takes twice as long to complete. This happens even if the code in the event is not triggered. I've added break points and logging to check this. The event isn't being entered (unless I open another spreadsheet of course).</p>
  
  <p>We also have a custom VSTO add-in for Excel. I've uninstalled this but it doesn't make any difference. I've tested moving the interop workbook open code into the add-in and have managed to get fast execution times but the senior developers would prefer I don't put the code in there. So my question is why does wiring up the interop workbook open event cause such an increase in execution time and is there a way to prevent this that doesn't involve moving the code into the add-in? I'm using Excel 2010.</p>
  
  <p>Relevant code below:</p>
  
  <pre><code>var args = new object[] {"RateProcess", "StandardRating.xls"};
  
  _spreadsheet = new Application();
  Workbooks workbooks = _spreadsheet.Workbooks;
  
  _commonWorkbook = workbooks.Open("StandardRating.xls", 0, false, 5, "", "", true,
      XLPlatform.xlWindows, "\t", true, false, 0, false, false, XLCorruptLoad.xlNormalLoad);
  
  _specialisedWorkbook = workbook.Open("SpecialisedRating.xls", 0, false, 5, "", "", true, XlPlatform.xlWindows, "\t", true, false, 0, false, false, XlCorruptLoad.xlNormalLoad);
  
  // This line causes the problem.
  _spreadsheet.WorkbookOpen += spreadsheet_WorkbookOpen;
  
  _spreadsheet.GetType().InvokeMember("Run", BindingFlags.Default | BindingFlags.InvokeMethod, null, _spreadsheet, args);
  </code></pre>