Attach to existing Excel Instance

c#, excel, excel-interop, interop, marshalling

Solution

`Marshal.GetActiveObject()` doesn't take a process ID as a parameter. What you want is:

Marshal.GetActiveObject("Excel.Application");

Note that this doesn't require keeping track of the process at all, there just needs to be one.

It gets a lot more complicated if you can have multiple processes and want to attach to a specific one. That is where the answer to the other question comes in.

There is also a good article at http://blogs.msdn.com/b/andreww/archive/2008/11/30/starting-or-connecting-to-office-apps.aspx with a more full description of different ways of launching excel. Note that not all of them are necessarily up to date with Excel 2013, where having a single process for all Excel windows complicates things. For your purposes though, the `GetActiveObject` solution should be fine.

Problem

I'm trying to determine whether or not an instance of Excel of running with a particular file open, and if so attach to it so I can control that instance. I've searched around and the majority of what I've got have come from this question. It has a reference to another site, but unfortunately it's dead for me so I cannot read up on it. My code so far is; ``` //Is Excel open? if (Process.GetProcessesByName("EXCEL").Length != 0) { Process[] processes = Process.GetProcesses(); foreach (Process process in processes) { //Find the exact Excel instance if (process.ProcessName.ToString() == "EXCEL" && process.MainWindowTitle == ("Microsoft Excel - " + fileName)) { //Get the process ID of that instance int processID = (int)Process.GetProcessById(process.Id).MainWindowHandle; //Attach to the instance... Excel.Application existingExcel = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject(process.Id); } } } ``` So far I've managed to get the process ID of the instance I want to attach to, but I'm lost when it comes to using that ID. Any ideas on how to proceed?

Original source

Related problems