I have a macro that open several files in one folder and copy one sheet to a Main File…
Here is a part of my code
x = 1 While x <= UBound(openfiles) Workbooks.Open Filename:=openfiles(x) Sheets("Sheet1").Copy After:=crntfile.Sheets(crntfile.Sheets.Count) x = x + 1 Wend
Sheets("Sheet1").Copy i would like to close the file
x before looping to
I tried with
Workbooks(x).Close SaveFiles:= False but it closes instead my main file
crntfile and not the file
Thx for the help
You want to get a handle on that opened workbook while opening it. To do that create a workbook variable and set it to the opened workbook.
Also notice I specifically referenced that workbook when copying (
openedWorkbook.Sheets("Sheet1").Copy) this is because the fact that you opened a new file means it is not the active file and when you just use
cells or many object referenced) without explicitly declaring from which parent object this child comes Excel uses the Active parent object. Sometime this is wrong. It is best to explicitly declare where you are referencing things from so there are no surprises.
Dim openedWorkbook As Workbook x = 1 While x <= UBound(openfiles) Set openedWorkbook = Workbooks.Open(Filename:=openfiles(x)) openedWorkbook.Sheets("Sheet1").Copy After:=crntfile.Sheets(crntfile.Sheets.Count) openedWorkbook.Close SaveFiles:=False x = x + 1 Wend
You could simply do:
The way you ave it right now is opening
x is an index of the
Workbooks Collection object.
Workbooks(x) is NOT the same as the file you have opened within that loop.