Home » excel » excel – Close File with VBA

excel – Close File with VBA

Posted by: admin May 14, 2020 Leave a comment

Questions:

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

After the Sheets("Sheet1").Copy i would like to close the file x before looping to x+1.
I tried with Workbooks(x).Close SaveFiles:= False but it closes instead my main file crntfile and not the file x

Thx for the help

How to&Answers:

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 Sheets (or range or 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

Answer:

You could simply do:

Workbooks(openfiles(x)).Close

The way you ave it right now is opening Workbooks(x), where x is an index of the Workbooks Collection object. Workbooks(x) is NOT the same as the file you have opened within that loop.