Click here to Skip to main content
15,896,730 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi I have a c# program, I need to connect to and use an instance of excel from within the program. My code is:

C#
Microsoft.Office.Interop.Excel.Application exApp = null;
try
{
  exApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
}
catch (Exception err)
{
   MessageBox.Show("no excel running, starting new one");
}
if (!exApp.Visible)
{
   exApp = new Microsoft.Office.Interop.Excel.Application();
}


I start excel, then start the c# program, and the catch part of the try/catch block executes. My program then starts a new instance of excel. So now I have 2 instances of excel running, the one that I started maually, and the one started by my program. When I trigger this code again, the c# program finds the instance of excel that it started, and I don't see the "no excel running..." message. It seems that the call to getactiveobject only works if my program started the instance of excel... help! I want my program to find any instance of excel, not just the one that it started... (kind of new to c#, .net, ...) THanks!
Posted
Updated 18-Feb-16 9:17am
v2

 
Share this answer
 
Comments
Member 10816215 13-May-14 17:00pm    
Thanks for your response. As you can see in my code snippet, I am using Marshal.GetActiveObject. It isn't working, I get an unhandled exception of type ....
Maciej Los 14-May-14 11:54am    
Isn't working is not informative at all! If you get unhandled exception, it means there is no active Excel application ;)
Follow the link and find out how to handle it ;)
Maciej Los 14-May-14 11:57am    
BTW: Why do you create another instance of Excel, if it isn't visible?
if (!exApp.Visible)
{
exApp = new Microsoft.Office.Interop.Excel.Application();
}
Have a look at this CodeProject article Finding and Listing Processes in C#[^]

On a similar question previously King_Fisher[^] also suggested this link http://stackoverflow.com/questions/4722198/checking-if-windows-application-is-running[^]. If this last link works for you then King_Fishers solution is here[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900