Create a new workbook and add sheets

H

HSalim[MVP]

Hi,
I am parsing a text file into component parts:

I want to open a new workbook, add a few worksheets, ad data, save file.
I can add the workbook but I can't seem to add worksheets to it

How can I fix the code below?
Thanks
Habib

----------------------
SrcFile = GetFile()
XLFile = Left(srcFile, Len(srcFile) - 4) & ".xls"
Set wkbook = Workbooks.Add()

wkbook.Activate

wksheets = Array("Invoice", "Payment", "Reference", "Summary", "Other")
For i = 0 To UBound(wksheets)
Worksheets.Add(Before:=Worksheets(Worksheets.Count)).Name = "test"
ActiveSheet.Name = wksheets(i)
Next
 
D

Dave Peterson

I'd use:

Dim wkSheets As Variant
Dim i As Long
Dim wkBook As Workbook

Set wkBook = Workbooks.Add(1) 'single sheet
wkBook.Worksheets(1).Name = "deletemelater"

wkSheets = Array("Invoice", "Payment", "Reference", "Summary", "Other")
For i = LBound(wkSheets) To UBound(wkSheets)
With wkBook
.Worksheets.Add(Before:=.Worksheets(Worksheets.Count)).Name = wkSheets(i)
End With
Next i

Application.DisplayAlerts = False
wkBook.Worksheets("deletemelater").Delete
Application.DisplayAlerts = True
 
D

Dave Peterson

There's a typo in my code!!!

..Worksheets.Add(Before:=.Worksheets(Worksheets.Count)).Name = wkSheets(i)
should be:
..Worksheets.Add(Before:=.Worksheets(.Worksheets.Count)).Name = wkSheets(i)

Those leading dots mean that those items belong to the object in the previous
"With" statement.
 
H

HSalim[MVP]

Dave,
thanks for that. That did the trick.

While tinkering with the code, I found another way.

wkSheets = Array("Invoice", "Payment", "Reference", "Summary", "Other")

Application.SheetsInNewWorkbook = UBound(wkSheets) + 1
Set wkBook = Workbooks.Add
For i = LBound(wkSheets) To UBound(wkSheets)
With wkBook
.Sheets(i + 1).Name = wkSheets(i)
End With
Next i


Regards
Habib
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top