Click here to Skip to main content
15,885,914 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Kindly please look at below code, which is about to export to excel file. Visual Studio doesn't run it. What is wrong with this code?
Please see the screenshot from the link:

https://yourimageshare.com/ib/SzbwxQ7g9t[^]

VB.NET
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


What I have tried:

I tried the code I wrote. But no luck.
Posted
Updated 21-May-23 3:11am

You have not qualified the object names so the system knows which types you are referring to. Try changing the Dim statements to:
VB
Dim excel As Microsoft.Office.Interop.Excel.Application = New Microsoft.Office.Interop.Excel.Application
Dim workbook As Microsoft.Office.Interop.Excel.Workbook = New Microsoft.Office.Interop.Excel.Workbook
Dim worksheet As Microsoft.Office.Interop.Excel.Worksheet = workbook.ActiveSheet


[edit]
Here is a tested sample that should do what you want:
VB.NET
Imports System.IO
Imports Excel = Microsoft.Office.Interop.Excel

Module XLTest
    Sub Main()
        Dim xlApp As Excel.Application = New Excel.Application()
        If xlApp Is Nothing Then
            Console.WriteLine("Error: Excel is not properly installed.")
            Return
        End If
        Dim xlWorkBook As Excel.Workbook
        xlWorkBook = xlApp.Workbooks.Add(Type.Missing)

        Dim xlWorkSheet = xlWorkBook.Sheets.Add(Type.Missing)
        xlWorkSheet.Cells(1, 1) = "Value1"
        xlWorkSheet.Cells(2, 1) = "Value2"
        xlWorkBook.SaveAs("d:\Actor.xlsx")

        xlWorkBook.Close(True, Type.Missing, Type.Missing)
        xlApp.Quit()

        Console.WriteLine("Excel test complete")
    End Sub
End Module


[/edit]
 
Share this answer
 
v3
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900