Hi there,
My program runs and after running creates some data in datagridview. I export the data to an excel file. Till now all things are okay, but I want to have the excel file open and export the second iterations data to the same file but different sheet. I have done everything but it gave me an error. Here is the pieces of code related to exporting.

Dim xlApp As New excel.Application
        Dim xlWBook As excel.Workbook = xlApp.Workbooks.Add(excelName)
       
        Dim xlWSheet As excel.Worksheet = CType(xlWBook.Worksheets(1), excel.Worksheet)
        If xlApp.ActiveWorkbook.Name = "Export.xlsx" Then
            xlWBook.Worksheets.Add(itr)
            xlWSheet.Name = DataFile

        End If

Every time it opens a new workbook(Second line) I cannot create new worksheet at the current workbook. I tried to put the xlapp.workbooks.add(excelname) in a condition if but it gave me an error that it is not referenced.
Thank you for any help,

What is itr ?

I don't think that you are creating a sheet the first time around

Dim xlWSheet As excel.Worksheet = CType(xlWBook.Worksheets(1), excel.Worksheet)

This selects an existing sheet, not adding one.

This should be adding:

dim newsheet as excel.worksheet
newsheet = wlWBook.worksheets.add

PS: Use newsheet2 for a second sheet.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.