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:
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):
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.
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:
I have made the class module available as a textfile which can viewed or saved from here.