add sheets to Excel via VB.net

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Stevecb
    New Member
    • Jul 2010
    • 13

    add sheets to Excel via VB.net

    Hello
    I'm using vb.net and creating an Excel ss. I'm trying to add sheets and name them. So far I have...
    Code:
    Imports Excel = Microsoft.Office.Interop.Excel
    
    Public Class Form1
        Private Sub Button1_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles Button1.Click
    
            Dim xlApp As Excel.Application
            Dim xlWorkBook As Excel.Workbook
            Dim xlWorkSheet As Excel.Worksheet
            Dim misValue As Object = System.Reflection.Missing.Value
    
            Dim intCount As Short ' from 0 to 255 - should be sufficient. Integer would add unnecessary "space"
    
            xlApp = New Excel.ApplicationClass
            xlWorkBook = xlApp.Workbooks.Add(misValue)
            xlWorkSheet = xlWorkBook.Sheets("sheet1")
    
            ' add new worksheets & name worksheets ----------------------------
            xlApp.Range("A50:I50").EntireColumn.AutoFit()
           
            With xlWorkBook
                .Sheets("Sheet1").Select()
                '.Sheets("Sheet1").Name = "config"
    
                intCount = 1
    
                'use FOR Instead of While
                'Insert sheet(s) 1 - 7 ( Takoro #1 - Takoro #7 )
                For intCount = 1 To 5
    
                    .Worksheets.Add(After:=.Worksheets(intCount)) 'INSERT AFTER LAST WORKSHEET 
                    'Use counter variable properly to rename all sheets accordingly
                    .Sheets(intCount).Name = "Taroko # " & intCount.ToString()
                Next
    
                .Worksheets.Add(Before:=.Worksheets(1)) 'Add config sheet last. BEFORE Takoro #1
                .Sheets(1).Name = "config" 'Config is now the first sheet
                xlApp.Visible = True
            End With
            End Sub
    a couple of problems, one the data that is supposed to be on the config tab is on Taroko #1 (sheet2) and 2nd there are extra sheets added, sheet 10, 2 and 3 on the furthest to the right.

    thanks for any help.
Working...