Checking if an Excel Workbook is open

后端 未结 7 1072
孤街浪徒
孤街浪徒 2020-12-30 05:22

Is there a way to see if an Excel Workbook, say DataSheet.xls, is open (in use) or not? I would like to close that Workbook if it is opened.

相关标签:
7条回答
  • 2020-12-30 06:22

    martin's answer does not work if Excel Application is not currently running. You may want to modifiy the code as following :

    static bool IsOpened(string wbook)
    {
        bool isOpened = true;
        Excel.Application exApp;
    
        try
        {
            // place the following line here :
            exApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
            // because it throws an exception if Excel is not running.
            exApp.Workbooks.get_Item(wbook);
        }
        catch (Exception)
        {
            isOpened = false;
        }
        return isOpened;
    }
    

    Thank you for your attention. Regards

    0 讨论(0)
提交回复
热议问题