creating a new sheet in different workbook

lezawang

Well-known Member
Joined
Mar 27, 2016
Messages
1,805
Office Version
  1. 2016
Platform
  1. Windows
Hi
The code below is working. I have 2 workbooks. Workbooks(1) has the code. When the user enter x = 2
the code below will create a worksheet in Workbooks(2) after worksheets(1). It is working but I wonder, in line 4, why I did not have to do this

Rich (BB code):
Workbooks(x).Worksheets.Add after:=Workbooks(x).Worksheets(1)

It will create the sheet in workbooks(2) anyway. Is that because of Workbooks(x=2).worksheets.Add? Thank you very much.


Rich (BB code):
Sub ws_add_using_collection()
    Dim x As Integer
    x = InputBox("which book")
    Workbooks(x).Worksheets.Add after:=Worksheets(1)
End Sub
 

Excel Facts

How to calculate loan payments in Excel?
Use the PMT function: =PMT(5%/12,60,-25000) is for a $25,000 loan, 5% annual interest, 60 month loan.
Code:
after:=Worksheets(1)
Just tells it where to add the new sheet & as there is always at least 1 sheet, it will work.
If you tried to add a sheet as the last sheet (ie sheets.count) you might get an error, or the new sheet might be in the wrong place.
 
Upvote 0

Forum statistics

Threads
1,214,392
Messages
6,119,257
Members
448,880
Latest member
aveternik

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top