Search code examples
c#excelexcel-dna

Get the current Workbook Object in C#


I've been writing an application in C# which creates Custom Document properties in an Excel spreadsheet, I have a function for this which takes in a Workbook Object...

However, actually getting the current Workbook object is proving to be quite annoying, I am using ExcelDNA to add functionality, however, I can't seem to pass my function a valid Workbook COM object.


Solution

  • This is the way I am currently doing it it seems to work really well

    using Excel = Microsoft.Office.Interop.Excel;      
    

    Then you get active workbook

    //Gets Excel and gets Activeworkbook and worksheet
    Excel.Application oXL;
    Excel.Workbook oWB;
    Excel.Worksheet oSheet;
    oXL = (Excel.Application)Marshal.GetActiveObject("Excel.Application"); 
    oXL.Visible = true;
    oWB = (Excel.Workbook)oXL.ActiveWorkbook; 
               
    docProps = oWB.CustomDocumentProperties
    

    Then I would try what you have and see how it works

    Hope this helps