When developing export capabilities for my .NET application to Microsoft Word and Microsoft Excel, I noticed that whenever I created a new document through COM automation, a new instance of either Microsoft Word or Microsoft Excel would be opened, resulting in many instances living in the Windows taskbar.

On Windows 7 this wasn’t too noticeable, since instances of Word or Excel would always have their own taskbar icon (or perhaps I had taskbar grouping off), but it was definitely becoming a problem on Windows XP. I set out to find out how I could open the running instance of Microsoft Word or Microsoft Excel rather than create a new one, so I could add a new document or worksheet to it.

This is the required code to create a new instance of Microsoft Excel:

using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excel = null;
excel = new Microsoft.Office.Interop.Excel.Application();
if(excel == null) { /* report error */ }

To open a Microsoft Word instance through .NET automation, do:

using word = Microsoft.Office.Interop.Word;
Word.Application excel = null;
word = new Microsoft.Office.Interop.Word.Application();
if(word == null) { /* report error */ }

Now, to open the running instance of Excel (if there is one), the code must be changed to:

using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excel = null;
try
{
  excel = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
}
catch (COMException)
{
}
if (excel == null) excel = new Microsoft.Office.Interop.Excel.Application();
if(excel == null) { /* report error */ }

And for Microsoft Word:

using Word = Microsoft.Office.Interop.Word;
Word.Application excel = null;
try
{
  word = (Word.Application)Marshal.GetActiveObject("Word.Application");
}
catch (COMException)
{
}
if (word == null) word = new Microsoft.Office.Interop.Word.Application();
if(word == null) { /* report error */ }

If there is an instance available, a new Microsoft Word document or Microsoft Excel workbook you subsequently create will now be added to the running instance.