Click to See Complete Forum and Search --> : Copy column heading from previous sheet in excel using vb.net


Alisa
January 26th, 2006, 05:52 PM
I filling in an excel spreadsheet with a SQL dataset. Once the data fills up the first excel spread sheet, it adds a new sheet and continues the filling in the data. I want to take the column headings of the previous sheet and paste them to the new sheet before it continues with filling in the data. I looked at the copy method but it is intended to copy the whole sheet. I only want the headings.
Any suggestions?

Thank you.

Gizmo001
January 27th, 2006, 09:50 AM
Dim Column1Header as string

Put the above statement outside the For Loop.

While you are in the first sheet, copy the column heading to the string:

Column1Header = 'Header value of Column1, for example = FirstExcelWorksheet.Cell (1,2).value


When you define the new sheet immediately assign to the cell the value

FirstExcelWorksheet.Cell (1,2).value = Column1Header


Hope this is clear.

Good luck.

Alisa
January 27th, 2006, 11:59 AM
For reason it didn’t work, maybe I did it incorrectly (okay I did wrong  ).... I also forgot to mention, I will not know how columns I will be returning.

I have been using
ds.Tables(0).Columns.Count - 1
To determine how many time to loop though to get the column heading. Also I did place that bit code into a separate function.

Here is a bit of that code:

Dim columnName1 As String
columnCount = ds.Tables(0).Columns.Count
For x = 0 To columnCount - 1 'populates column heading by incremanting though the letter heading
columnName1 = ds.Tables(0).Columns.Item(x).ColumnName
.Range(Chr(y) & i.ToString).Value = columnName1
y += 1
Next

I do pass back the excel sheet with the name already on the tab. Then as each sheet is added it added the new name to tab.


Any suggestions?

Thank you

Gizmo001
January 27th, 2006, 12:14 PM
Let me try.

Your code:

Dim columnName1 As String
columnCount = ds.Tables(0).Columns.Count
For x = 0 To columnCount - 1 'populates column heading by incremanting though the letter heading
columnName1 = ds.Tables(0).Columns.Item(x).ColumnName
.Range(Chr(y) & i.ToString).Value = columnName1
y += 1
Next


Let us assume that x=0 goes to column 1 in Excelsheet, x=1 goes to column 2 and top row has the column name. Instead of using the range command, use

worksheetname.cells(1,x+1).value = columnName1

You don't need another variable y. Good luck. Hope it works.