Gharbad_The_Weak
Gharbad_The_Weak

Reputation: 25

How to list all open Excel workbooks

I'm writing a c# console app with .net 4.7.1. I have several open Excel workbooks on my computer. I am trying to list all of the open Excel workbooks on my computer.

I've looked at several SO posts and have put this code together that should list all of the open Excel workbooks on my computer but when I run the code none of the open Excel workbooks get listed.

using System;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;

namespace ExcelWorkbooks
{
    class Program
    {
        static void Main(string[] args)
        {
            Application oXL = new Microsoft.Office.Interop.Excel.Application();
            oXL = (Application)Marshal.GetActiveObject("Excel.Application");
            Console.WriteLine("starting");
            foreach (Microsoft.Office.Interop.Excel.Workbook blah in oXL.Workbooks)
            {
                Console.WriteLine(blah.Name.ToString());
            }
            Console.WriteLine("ending");
            Console.ReadLine();
        }
    }
}

the output should be

starting

there should be a list of open Excel workbooks here

ending

but instead this is what is output

starting

ending

If someone could point me in the right direction of what needs to be added/subtracted or changed in my code so it will list all of the open Excel workbooks on my computer I would appreciate it. Thanks in advance.

EDIT: I was playing around with this and I closed the 2 Excel workbooks that were open. I then looked in the task manager and saw that even after I closed all of the Excel workbooks there were like 10 "EXCEL" processes still running. I closed all of "EXCEL" processes and then opened the 2 Excel workbooks again. Now the code above lists the 2 open Excel workbooks. So, I guess the question has changed somewhat to why were there 10 "EXCEL" processes running when I only had 2 open workbooks and more importantly going forward how should I deal with this so if there are additional "EXCEL" processes I can handle this so it will show the open Excel workbooks. Thanks.

Upvotes: 0

Views: 1378

Answers (1)

DisplayName
DisplayName

Reputation: 13386

to list the current Excel instance workbooks names, just change:

Application oXL = new Microsoft.Office.Interop.Excel.Application();
oXL = (Application)Marshal.GetActiveObject("Excel.Application");

to:

 Application oXL = (Application)Marshal.GetActiveObject("Excel.Application");

you may want to add some Try/Catch block to handle the case of no Excel instance available

Upvotes: 1

Related Questions