create new workbook

User avatar
sal21
PlatinumLounger
Posts: 4374
Joined: 26 Apr 2010, 17:36

create new workbook

Post by sal21 »

I have just have active workbook.
I need to create a new workbook via vba code and add sheet1 and sheet2 from the active workbook and save the new workbook in c:\my_dir\mynewvb.xls....

User avatar
HansV
Administrator
Posts: 78647
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: create new workbook

Post by HansV »

Like this:

Code: Select all

Sub CreateWorkbook()
  ' Copy sheets to new workbook
  ActiveWorkbook.Worksheets(Array("Sheet1", "Sheet2")).Copy
  ' Close and save the new workbook
  ActiveWorkbook.Close SaveChanges:=True, Filename:="c:\my_dir\mynewvb.xls"
End Sub
Best wishes,
Hans

User avatar
sal21
PlatinumLounger
Posts: 4374
Joined: 26 Apr 2010, 17:36

Re: create new workbook

Post by sal21 »

tKS but i dont want to close the active workbook where is the code...

User avatar
HansV
Administrator
Posts: 78647
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: create new workbook

Post by HansV »

The line

ActiveWorkbook.Worksheets(Array("Sheet1", "Sheet2")).Copy

creates a new workbook, and this new workbook becomes the active workbook. So the line

ActiveWorkbook.Close SaveChanges:=True, Filename:="c:\my_dir\mynewvb.xls"

acts on the new workbook, not on the workbook with the code. When the new workbook is closed, the workbook with the code becomes the active workbook again.
Best wishes,
Hans

User avatar
Don Wells
5StarLounger
Posts: 689
Joined: 27 Jan 2010, 16:45
Location: Ottawa, Ontario, Canada

Re: create new workbook

Post by Don Wells »

HansV wrote:Like this:

Code: Select all

  ' Copy sheets to new workbook
  ActiveWorkbook.Worksheets(Array("Sheet1", "Sheet2")).Copy
The above line of code certainly works as advertised by Hans, but I need some help understanding it. I would have expected the two worksheets to be copied to the clipboard. Also I see nothing that obviously creates a new workbook. Is there something happening here by default?
:scratch:
TIA
Regards
Don

User avatar
HansV
Administrator
Posts: 78647
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: create new workbook

Post by HansV »

From the help for the Copy method of the Worksheet(s) object:
Remarks
If you don't specify either Before or After, Microsoft Excel creates a new workbook that contains the copied sheet.
Best wishes,
Hans

User avatar
Don Wells
5StarLounger
Posts: 689
Joined: 27 Jan 2010, 16:45
Location: Ottawa, Ontario, Canada

Re: create new workbook

Post by Don Wells »

HansV wrote:From the help for the Copy method of the Worksheet(s) object:
Thank you Hans :thankyou:
:blush: If all else fails, read the manual. I am embarrassed. :blush:
Regards
Don