I have a project that’s been running for 15 years that is suddenly giving an error when trying to create an Excel file on both my local machine and my user’s machine at their office. To test, I’ve created a new project (Windows 10, Windows Forms, .Net Framework 4.7.2), installed the Microsoft.Office.Interop.Excel NuGet package, added a button to a form and in the click event, set the value of a cell to “Hello World” and I’m still getting the error. I can’t find anything online about this error either outside of suggestions to repair Excel which I’ve already done to no avail.
Here’s the error:
System.InvalidCastException: ‘Unable to cast COM object of type ‘Microsoft.Office.Interop.Excel.ApplicationClass’ to interface type ‘Microsoft.Office.Interop.Excel._Application’. This operation failed because the QueryInterface call on the COM component for the interface with IID ‘{000208D5-0000-0000-C000-000000000046}’ failed due to the following error: Element not found. (Exception from HRESULT: 0x8002802B (TYPE_E_ELEMENTNOTFOUND)).’
And here’s the vb.net code:
Dim xlApp As Excel.Application = New Excel.Application()
Dim xlWb As Excel.Workbook = xlApp.Workbooks.Add() ' fails on this line
Dim xlSheet As Excel.Worksheet = CType(xlWb.Sheets(1), Excel.Worksheet)
xlSheet.Cells(1, 1).FormulaR1C1 = "hello world!"
xlApp.Workbooks(1).SaveAs("testing.xls")
xlApp.Visible = True
All of the above is with Option Strict On
If I make another project, leave Option Strict Off, don’t download the NuGet package and use the below code, I don’t have any issue
Dim xlApp As Object = Nothing
Dim xlBook As Object
Dim xlSheet As Object
xlApp = CreateObject("Excel.Application")
xlApp.Visible = False
xlApp.DisplayAlerts = False
xlBook = xlApp.Workbooks.Add
xlSheet = xlBook.Sheets(1)
xlSheet.Cells(1, 1).FormulaR1C1 = "Hello world!"
xlApp.Visible = True