below code is about to export to excel file. Visual Studio sends the error in the picture. What is wrong with this code?
Imports Microsoft.Office.Interop.Excel
Module Module3
Public Sub OOO()
Dim excel As Application = New Application
Dim workbook As Workbook = New Workbook
Dim worksheet As Worksheet = workbook.ActiveSheet
worksheet.Name = "Export as Excel Project"
worksheet.Cells(1, 1) = "Value1"
worksheet.Cells(2, 1) = "Value2"
worksheet.SaveAs("d:\Actor.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault)
workbook.Close()
End Sub
End Module
Your code is wrong starting by first Dim excel line. You expect that would be an Excel.Application but it is not, it is System.Windows.Application (as I understand from error window). If that line were correct, next line is trying to create an unrelated Workbook object. Instead try:
Sub Main
Dim xl As Microsoft.Office.Interop.Excel.Application = New Microsoft.Office.Interop.Excel.Application()
Dim workbook = xl.Workbooks.Add()
Dim worksheet As Worksheet = CType(workbook.ActiveSheet, Worksheet)
worksheet.Name = "Export as Excel Project"
worksheet.Cells(1, 1) = "Value1"
worksheet.Cells(2, 1) = "Value2"
worksheet.SaveAs("d:\Actor.xlsx", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault)
workbook.Close()
xl.Quit()
End Sub
Note that file extension is XLSX, not XLS for current versions of Excel (for a long time really, and Excel wouldn't open it without a warning if you happen to save as XLS).