Checking if an Excel Workbook is open

后端 未结 7 1231
孤街浪徒
孤街浪徒 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:14

    The right way is to examine the Application.Workbooks object. In VBA you would write:

    Dim wb as Workbook
    On Error Resume Next                       '//this is VBA way of saying "try"'
    Set wb = Application.Workbooks(wbookName)
    If err.Number = 9 then                     '//this is VBA way of saying "catch"'
        'the file is not opened...'
    End If
    

    In other words, Workbooks is an array (or in VBA terms, Collection) of all open workbooks.

    In C# the following code works:

        static bool IsOpened(string wbook)
        {
            bool isOpened = true;
            Excel.Application exApp;
            exApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
            try
            {
                exApp.Workbooks.get_Item(wbook);
            }
            catch (Exception)
            {
                isOpened = false;
            }
            return isOpened;
        }
    

    You will probably want to pass the reference to Excel.Application yourself.

提交回复
热议问题