0

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,

2
Contributors
1
Reply
5
Views
6 Years
Discussion Span
Last Post by adam_k
0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.