Using Access 2010, WinXP. I’m trying to iterate through a collection of folders, collecting values from each of the Excel files in each folder to add to a table in my database. The problem is that even though I’m closing the workbook each time, it must not be closing fast enough, because if the same filename appears in two consecutive folders, I get an error message:
Run-time error '1004':
A document with the name 'someWorkbook.xls' is already open.
Here’s my code:
sub traverse()
Dim fso As filesystemobject
Dim fObj As File
Dim fldObj As Folder
Dim fCol As Files
Dim xlApp As Excel.Application
dim xlBk as Excel.Workbook
Set xlApp = New Excel.Application
Set fso = New filesystemobject
For Each fldObj In fso.GetFolder("c:\basePath").SubFolders
Set fCol = fldObj.Files
For Each fObj In fCol
If UCase(Left(fso.GetExtensionName(fObj.Name), 3)) = "XLS" Then
Set xlBk=xlApp.workbooks.open(fObj.path)
getData(xlBk)
xlBk.close false
DoEvents
End If
Next
Next
End Sub
I tried quitting the Excel instance and starting a new one in the For Each fObj loop, as follows:
set xlApp=new Excel.Application
Set xlBk=xlApp.workbooks.open(fObj.path)
getData(xlBk)
xlBk.close false
DoEvents
xlApp.quit
DoEvents
but that only ended up opening a whole bunch of Excel instances without quitting them, as when it crashed I checked the task manager and found about 30 Excel instances.
Is there something else I can do to guarantee that my code doesn’t proceed until the Excel action triggered by .Close or .Quit has completed?
@sigil Answered his own question in comments.