com exception excel InteropServices.COMException - c#

0

I am receiving System.Runtime.InteropServices.COMException when running the below method from main()

I want to get true and later access the sheet if excel is opened on system. I am making sure excel is opened and sheet1 is there but I get false and the error above.

using Excel = Microsoft.Office.Interop.Excel;

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

EDIT: when I run VS2019 as admin , I received more infor on error

Operation unavailable (Exception from HRESULT: 0x800401E3 (MK_E_UNAVAILABLE))

c#
excel
com
comexception
asked on Stack Overflow Jun 28, 2019 by user1207289 • edited Jun 28, 2019 by user1207289

1 Answer

1

I think your issue is Visual Studio running in a different context to Excel.

I tried a slightly modified version of your code and it works just fine when running Visual Studio NOT as admin (same user as excel was opened with).

Might be worth checking you are using the right version of the interop dll also.

public bool IsExcelOpened()
        {
            bool isOpened = false;

            try
            {
                Excel.Application exApp;
                Excel.Worksheet xlWorksheet;
                exApp = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application") as Excel.Application;
                if(exApp != null)
                {
                    xlWorksheet = (Excel.Worksheet)exApp.ActiveSheet;
                    isOpened = true;
                }
            }
            catch { }
            return isOpened;
        }
answered on Stack Overflow Jun 28, 2019 by HockeyJ

User contributions licensed under CC BY-SA 3.0