Search code examples
c#excelappdomainexcel-dna

ExcelDnaUtility.Application creating a new book (Book1), so first new book in excel is Book2


I have a C# ExcelDna project that, in general, has no issues. However, I use ExcelDna.Application to open a spreadsheet during AutoOpen() (an xlam). I noticed that the first "USER CREATED" workbook, using Excel Menus is Book2. To isolate this, I did the code below. Even when not opening any workbooks, just referring to ExcelDna.Application seems to create a shadow workbook that moves the workbook counter to Book2. Is this a known thing, a bug? or something I'm doing wrong! Thanks/Cheers

public class ExcelDNAXllEntry : IExcelAddIn
  {
      public void AutoOpen()
      {
          // EXCEL DNA  STUFF ---------------------------------------------------------------------------
          ComServer.DllRegisterServer();
          //-----------------------------------------------------------------------------------------------
          Application x = (Application)ExcelDnaUtil.Application;

I'd expect the first user opened book to be book1. There are no hard errors or error messages, just the odd behavior that I'd like to avoid. We have many users and if they start seeing Book2 I'll be answering lots of questions :)


Solution

  • When Excel loads your add-in, the COM object model is (typically) not yet initialised. I know of no other way to get Excel into a state where we can get to the Application COM object, other than by creating a new 'macro' type workbook behind the scenes. A consequence is the behaviour you report.

    I'd be very happy to incorporate an alternative approach in Excel-DNA.