views:

7000

answers:

2

I have a bunch of Excel workbooks that contain multiple worksheets. I want to loop through each workbook and export each worksheet into it's own new workbook. I want one worksheet in each new workbook.

Here's what I've got so far:

   Sub ExportWorksheet(ByVal worksheet As Excel.Worksheet, ByVal filePath As String)
      Dim xlApp As Excel.Application = New Excel.ApplicationClass
      Dim xlWorkBook As Excel.Workbook = xlApp.Workbooks.Add
      worksheet.Select()
      worksheet.Copy()
      xlWorkBook.Worksheets.Add()
      worksheet.Paste(Destination:=xlWorkBook)

      xlWorkBook.SaveAs(Filename:=filePath)

      xlWorkBook.Close(False)
      xlApp.Quit()
   End Sub
+1  A: 

Within Excel this would be accomplished by copying the worksheet to a new workbook, not by creating a new workbook then adding the worksheet to it. This is achieved by using Worksheet.Copy without specifying where in the workbook you want to place the copied worksheet.

More reading: http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.worksheet.copy(VS.80).aspx

Lunatik
How do you access the newly created workbook with the new worksheet?
Gern Blandston
Nice answer Lunatik +1. Gern, you raise a good point. You'd have to access the workbook by name... which would be automatically generated. The Worksheet.SaveAs(string) approach has a similar problem in that you cannot get the workbook reference directly -- but in this case you at least do know the workbook name. So as long as you are willing to save the workbook (or want to) then the SaveAs approach is a little better.
Mike Rosenblum
A: 

Doh! worksheet.SaveAs(Filename:=filePath)

Gern Blandston
Yes, this works too if your goal is, ultimately, to save the workbook as well. Lunatik got it right though, you should give him the check mark for a correct answer.
Mike Rosenblum
Hmm.. ok, well there is at least one advantage to using .SaveAs(string) versus .Copy(): you will at least know the name of your workbook after the operation has completed. So this approach is actually better as long as one is willing (or needs) to save the workbook.
Mike Rosenblum