Search code examples
c#excelms-officeoffice-interopexcel-interop

Accessing an open Excel Workbook in C#


I need to access an excel file that is already open. I thought just inspecting the .Workbooks property that it would be there but it isn't. What is the right way to get a reference to the open workbook?

var app = new Microsoft.Office.Interop.Excel.Application();

// the count is 0 =(
app.Workbooks.Count == 0;

EDIT

I can get a reference to the Excel Application via...

app = (Excel.Application)Marshal.GetActiveObject("Excel.Application");

but app.Workbooks.Count is still 0 why isn't it able to get a reference to the opened workbook?


Solution

  • Instead of instantiating a new instance, check for an existing one:

    try
    {
      Microsoft.Office.Interop.Excel.Application app = 
          System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
    }
    catch
    {
      // Excel is not running.
    }