VSTO & .NET & Excel

November 25, 2007

Access running instances of Excel in VB

Filed under: .NET & Excel — Dennis Wallentin @ 10:49 pm

When automating Excel from VB we can either create new instances or access already running instances. In different scenarios different methods may be needed in order to get workable solutions.

In the first scenario we may need to access a running instance and if not we need to create a new one as the following sample shows:

getactiveobject.png

This is a rather simple method but it does the work and we can handle the situation if any error is raised.

In the second case we use a slightly different approach as the below code shows. The System.Diagnostic.Process class represents a Windows process. The sample uses the GetProcessesByName property to check if any Excel session is running or not. This approach is less ‘brutal’ then the above and offer also more options as it use the System.Diagnostic.Process (see also the other samples below):
 

processgetobject.png

In the third scenario another approach is used which is based on BindToMoniker. Unlike the above methods it works ‘botttom up’ (in the Excel’s object model) as it gets an interface pointer identified by the specified moniker, here the workbook file. The method provides the same functionality as the GetObject method in VB 6.    

tobindmoniker.png

In some scenarios we may want to start a new Excel session, allow the users to work with one or more workbooks and finally end the process. The following sample shows how we can achieve it:
 

start-end-session.png

Remark:
I have not tested how it works when using the Dual Core Processor and instantiate new Windows processes.

The final sample shows how we can get information for all running Excel instances with the System.Diagnostic.Process class:

document-sessions.png

I have made the class module available as a textfile which can viewed or saved from here

Kind regards,
Dennis

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.