copy a sheet to a close workbook - vba

lezawang

Well-known Member
Joined
Mar 27, 2016
Messages
1,805
Office Version
  1. 2016
Platform
  1. Windows
Hi
In the code below, this line of code
Code:
Set closedBook = Workbooks.Open("D:\Dropbox\excel\articles\example.xlsm")

Not sure why I need "Set closedBook". Let say I have one Workbook open, which is Workbooks(1). If I do this code

Code:
 Workbooks.Open("D:\Dropbox\excel\articles\example.xlsm")

Without "Set closeBook", would that guarantee that the second workbook is going to be Workbooks(2)?

If yes, then why I need to do "Set closedBook"

Another question please, why he did not define

Code:
 Dim ClosedBook as Workbook

Code:
Sub CopySheetToClosedWB()
Application.ScreenUpdating = False
 
    Set closedBook = Workbooks.Open("D:\Dropbox\excel\articles\example.xlsm")
    Sheets("Sheet1").Copy Before:=closedBook.Sheets(1)
    closedBook.Close SaveChanges:=True
 
Application.ScreenUpdating = True
End Sub

Source: https://www.automateexcel.com/vba/copy-worksheet/
 

Excel Facts

VLOOKUP to Left?
Use =VLOOKUP(A2,CHOOSE({1,2},$Z$1:$Z$99,$Y$1:$Y$99),2,False) to lookup Y values to left of Z values.
Without "Set closeBook", would that guarantee that the second workbook is going to be Workbooks(2)?
Nope, IMO it's always safer to create & use a variable to refer to other workbooks.

why he did not define
I've no idea, maybe you'd ask him, rather than us.
 
Upvote 0

Forum statistics

Threads
1,214,527
Messages
6,120,057
Members
448,940
Latest member
mdusw

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