Click here to Skip to main content
15,797,721 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:[^]

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)
    End Sub
End Module

What I have tried:

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

You have not qualified the object names so the system knows which types you are referring to. Try changing the Dim statements to:
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

Here is a tested sample that should do what you want:
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.")
        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.Close(True, Type.Missing, Type.Missing)

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

Share this answer
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