Can a sub return an object and reference to object to a calling Sub????

AlexB123

Board Regular
Joined
Dec 19, 2014
Messages
207
Hi all,

A few weeks ago I asked about creating new workbooks with specific numbers of sheets. I was given a code that stores the default number of sheets to be created in a new workbook, then changes the Application.SheetsInNewWorkbook property to the desired of new sheets, creates a workbook, and then restores the defaults.

I want to turn this into a function I can call from any macro ... Since I always set workbook references like so:

Code:
Dim aWorkbook As Workbook
Dim bWorkbook As Workbook

Set aWorkbook = Workbooks.Add
Set bWorkbook = Worbooks.Open("C:\\myHome\some.xlsx")

I want to know if it is possible to have newWB returned to a calling sub:

Code:
Public Sub addWBsheets(shtsNum As Integer)
Dim shtsCnt As Integer
Dim newWB As Workbook
  With Application
                  shtsCnt = .SheetsInNewWorkbook
     .SheetsInNewWorkbook = shtsNum
                  Set newWB = Workbooks.Add
     .SheetsInNewWorkbook = shtsCnt
                End With
End Sub

or if I can set a workbook reference directly by calling:

Code:
Set cWorkbook = Call addWBsheets(8)

Sorry if my language is confusing. Happy to provide details..
 

Excel Facts

Save Often
If you start asking yourself if now is a good time to save your Excel workbook, the answer is Yes
How about
Code:
Sub atest()
   Dim Awb As Workbook
   
   Set Awb = AddWb(5)
   Awb.Sheets(4).Select
End Sub
Function AddWb(Shts As Long)
   Dim shtsCnt As Integer
  
   With Application
      shtsCnt = .SheetsInNewWorkbook
      .SheetsInNewWorkbook = Shts
      Set AddWb = Workbooks.Add
      .SheetsInNewWorkbook = shtsCnt
   End With
End Function
 
Upvote 0

Forum statistics

Threads
1,224,829
Messages
6,181,218
Members
453,024
Latest member
Wingit77

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