0
votes

I have written a VBA macro in an excel spreadsheet that opens all workbooks in a specific location and pulls data out of those workbooks and validates and copies it to the active workbook. It then opens the next workbook in the directory and repeats the process until all files in the directory have been read through.

Everything works, except I cant seem to get the target workbooks to close once opened. This includes closing Excel. I have to kill the process in the task manager or in powershell to free the workbook from system memory.

Set fs = CreateObject("Scripting.FileSystemObject")
strExcelFileName = Dir(ThisWorkbook.Path & "\Certs\*.xls", vbNormal)
Set xlApp = CreateObject("Excel.Application")
Do While (strExcelFileName <> "")
      xlApp.Workbooks.Open (ThisWorkbook.Path & "\Certs\" + strExcelFileName)
      'code to run for each workbook opened
      ***xlApp.Workbooks.Close*** 'when present, Excel freezes
      strExcelFileName = Dir 'next file in directory
Loop

When the xlApp.Workbooks.Close line is present and called in the program, excel freezes every time. Without it, I can run through 3-5 workbooks before the system is overwhelmed and freezes. I then must kill those processes, move those files out, move 3 more in and repeat until all files have been processed this way. It takes about an hour and a half to go through 50.

What I am trying to do is have the workbook where the data is grabbed from closed before the next one is opened.

ActiveWorkbook.Close

This attempts to close the workbook where the macro is running, not the workbook that has been opened to be read from.

2

2 Answers

4
votes

You already have Excel open so you do not need to open another copy. Try:

Set WBookOther = Workbooks.Open(PathCrnt & FileNameCrnt)
  :
  :
WBookOther.Close SaveChanges:=False

This earlier answer of mine which cycles though every workbook in the current folder may help further.

3
votes

I ran your code without any problem whatsoever, but here's a cleaner alternative:

Dim strExcelFileName As String
Dim xlApp As Object
Dim wbk As Workbook

strExcelFileName = Dir(ThisWorkbook.Path & "\Certs\*.xls", vbNormal)
Set xlApp = CreateObject("Excel.Application")
Do While (strExcelFileName <> "")
      Set wbk = xlApp.Workbooks.Open(ThisWorkbook.Path & "\Certs\" _
          + strExcelFileName) ' set a reference to the workbook you're opening

      'code to run for each workbook opened
      'Your code should use the "wbk" reference to make sure
      ' you're accessing the correct workbook.

      wbk.Close ' close the workbook using the reference you set earlier

      strExcelFileName = Dir 'next file in directory
Loop