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....
create new workbook
-
- Administrator
- Posts: 78647
- Joined: 16 Jan 2010, 00:14
- Status: Microsoft MVP
- Location: Wageningen, The Netherlands
Re: create new workbook
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
Hans
-
- PlatinumLounger
- Posts: 4374
- Joined: 26 Apr 2010, 17:36
Re: create new workbook
tKS but i dont want to close the active workbook where is the code...
-
- Administrator
- Posts: 78647
- Joined: 16 Jan 2010, 00:14
- Status: Microsoft MVP
- Location: Wageningen, The Netherlands
Re: create new workbook
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.
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
Hans
-
- 5StarLounger
- Posts: 689
- Joined: 27 Jan 2010, 16:45
- Location: Ottawa, Ontario, Canada
Re: create new workbook
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?HansV wrote:Like this:
Code: Select all
' Copy sheets to new workbook ActiveWorkbook.Worksheets(Array("Sheet1", "Sheet2")).Copy
TIA
Regards
Don
Don
-
- Administrator
- Posts: 78647
- Joined: 16 Jan 2010, 00:14
- Status: Microsoft MVP
- Location: Wageningen, The Netherlands
Re: create new workbook
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
Hans
-
- 5StarLounger
- Posts: 689
- Joined: 27 Jan 2010, 16:45
- Location: Ottawa, Ontario, Canada
Re: create new workbook
Thank you HansHansV wrote:From the help for the Copy method of the Worksheet(s) object:
If all else fails, read the manual. I am embarrassed.
Regards
Don
Don