Copy column heading from previous sheet in excel using vb.net

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.




Answer this question

Copy column heading from previous sheet in excel using vb.net

  • Mattias Svensson

    Hi,

    If I understand correctly you have a bunch of data in SQL with same headings, right
    And you want to have the same headings in each sheet



  • Vince15

    Hi Alisa,

    You can do it this way:  (let's say your headings are from A1:F1 on sheet 1 and you want to copy them to sheet2) - the code would be like this:

    Globals.Sheet1.Range["A1", "F1"].Copy(Globals.Sheet2.Range["A1", "F1"]);

    Equvivalent code in VB.NET would be:

    Globals.Sheet1.Range("A1", "F1").Copy(Globals.Sheet2.Range("A1", "F1"))



     



  • JPlenert

    For reason it didn’t work, maybe I did it incorrectly (okay I did wrong J ).... 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



  • Copy column heading from previous sheet in excel using vb.net