Home » excel » c# – How can I open the current instance of Excel from my application?

c# – How can I open the current instance of Excel from my application?

Posted by: admin April 23, 2020 Leave a comment

Questions:

How can I open my Excel worksheet in the current open instance of Microsoft Excel? When I use my code, a new instance of Excel is opened.

 private Excel.Application xlApp;
 private Excel.Workbook xlWorkBook;
 private Excel.Worksheet xlWorkSheet;

 xlApp = new Excel.Application();
 xlApp.Visible = true;

 xlWorkBook = xlApp.Workbooks.Open(textBox1.Text);
 xlWorkSheet = (Excel.Worksheet)xlWorkBook.ActiveSheet;
How to&Answers:

You can do something like the following to get a reference to a running Excel instance (if there is one):

public Excel.Application TryGetExistingExcelApplication()
{
    try
    {
        object o = Marshal.GetActiveObject("Excel.Application");
        return (Excel.Application)o;
    }
    catch (COMException)
    {
        // Probably there is no existing Excel instance running, return null
        return null;
    }
}

Once you have a reference to a running instance, you can access it’s Workbooks collection.

One caveat: if you try to automate an existing Excel instance, you may get “server busy” exceptions. To avoid this, you can implement IOleMessageFilter error handlers. This article describes how to do it for automating Visual Studio; the technique is identical for automating Excel.