views:

305

answers:

1

Hi all,

Just after a little help with late binding.

I am trying to late bind excel and i don't have any issues doing that. It is only when I have more than one instance of excel open where I run into some problems.

I would like to be able to determine what instance of excel to bind to (and the link events etc.). Main reason being I have an application that opens a excel document from a third party tool and the events aren't handled. I want to be able to tap into the particular excel instance that I know is open to catch the events. Only problem is if excel is already open by the user (doesn't matter how).

If excel is opened after the bind, obviously, I don't get a problem. It is only when excel is already open.

It seems that the binding is done to the first instace that is open.

Here is the actual code:

 Type excelType = Type.GetTypeFromProgID("Excel.Application");

 // Throw exception if the type wasn't found
 if (excelType == null)
     throw new Exception(error);

 //Get the Excel.Application Type by creating a new type instance
 excelApplication = Marshal.GetActiveObject("Excel.Application");

 //Throw exception if the object couldn't be created
 if (excelApplication == null)
     throw new Exception(error);

 this.withEvents = withEvents;

 //Create link between the Word.Applications events and the ApplicationEvents2_WordEvents class
 if (this.withEvents)
 {
     excelEvents = new ExcelApplicationEvents();

     //holds the connection point references of the Word.Application object
     IConnectionPointContainer connectionPointContainer = excelApplication as IConnectionPointContainer;

     //Find the connection point of the GUID found from Red Gate's .Net Reflector
     Guid guid = new Guid("00024413-0000-0000-C000-000000000046");
     connectionPointContainer.FindConnectionPoint(ref guid, out connectionPoint);

     //Advise the Word.Application to send events to the event handler
     connectionPoint.Advise(excelEvents, out sinkCookie);

     excelEvents.WorkbookBeforeSaveEvent += new EventHandler<WorkbookEventArgs>(ExcelEventsWorkbookBeforeSaveEvent);
 }

Any Ideas?

Cheers,

Dale.

+1  A: 

Getting a particular instance of Excel requires that you make use of the AccessibleObjectFromWindow API.

This is explained well in the article Getting the Application Object in a Shimmed Automation Add-in by Andrew Whitechapel.

What you want, however, is to execute it using late binding. This is described in detail by divo here: How to use use late binding to get excel instance.

Mike Rosenblum