Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can I create 4th sheet in Excel ?

Status
Not open for further replies.

TekMem

Programmer
Jul 23, 2004
98
CA
Hi,

I am not able to create 4th sheet in Excel. Need help.

Thanks.

 
What have you tried? Have you tried using Excel's help? Have you tried to google insert worksheet excel?
 
Yes I did but I could not figure out.
It should be something
xlSheet = xlBook.Sheets.Add("sheet4")
or
xlSheet = xlBook.Sheets.insert ?

Nothing is working.
 
Try:
Code:
xlSheet = xlBook.Worksheets.Add
Then you can change the name of the worksheet.
djj
 
Code:
Dim xname As String = "adb"
        Dim xlApp As Excel.Application
        Dim xlBook As Excel.Workbook
        Dim xlSheet As Excel.Worksheet
xlApp = CType(CreateObject("Excel.Application"), Excel.Application)
        xlBook = CType(xlApp.Workbooks.Add, Excel.Workbook)
        Dim i As Integer = 1
        Do While i < 4

    xlSheet = CType(xlBook.Worksheets(i), Excel.Worksheet)


            xlSheet.Cells(10, 10) = "This is column B row 2"
            xlSheet.Cells(5, 5) = "This is column B row 2"

            xlSheet.Name = "Newsheet" & i

            i = i + 1
        Loop
 xlSheet.SaveAs("C:\Test.xls")

My code works if i is less than 4 , if it is less than 5 gives me error.
 
Pease help..How can I make my codes work if i < 5.

Thanks.
 
I think that your problem is that when you ceate a new workbook, you get 3 worksheets by default. Try going into Excel from the start menu and you will see that if you create a new workbook that it has sheet1,sheet2,sheet3

Thus if i is less than 4 your logic above would work ok, as there are 3 existing worksheets.

Thus I think you may just need to modify you logic to add a worksheet if i is greater than 4 - or maybe clear all worksheets from the workbook collection when you open the workbook and then put a worksheet.add into you loop

HTH
 
Try something like this:
Code:
Dim xname As String = "adb"
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
xlApp = CType(CreateObject("Excel.Application"), Excel.Application)
xlBook = CType(xlApp.Workbooks.Add, Excel.Workbook)
Dim i As Integer = 1
Do While i < 5
   Try
      xlSheet = CType(xlBook.Worksheets(i), Excel.Worksheet)
   Catch ex As Exception
      [COLOR=red]xlSheet = xlBook.Worksheets.Add[/color]
      xlSheet = CType(xlBook.Worksheets(i), Excel.Worksheet)
   End Try
   xlSheet.Cells(10, 10) = "This is column B row 2"
   xlSheet.Cells(5, 5) = "This is column B row 2"
   xlSheet.Name = "Newsheet" & i
   i = i + 1
Loop
xlSheet.SaveAs("C:\Test.xls")
djj
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top