Sub ProcessFromFolder()
'This macro opens each file in turn and extracts the data from it, records it in the database,
'closes the file, and moves on to the next file. The macro also records the file name so that
'it will only process a file if it has not been processed before. It uses a 'collection' for
'the file names.
Dim fso As Object, fld As Object, fil As Object
Dim coll As New Collection
Dim FileListWs As Worksheet
Dim SourceWs As Worksheet
Dim SourceWb As Workbook
Dim DestWs As Worksheet
Dim TotFiles As Long
Dim Counter As Long
Dim WasOpen As Boolean
Dim i As Long
Dim rowe As Long
Dim col As Long
Dim lastrow As Long
Dim errorflag As String
Application.ScreenUpdating = False
errorflag = ""
' Determine files processed already
Set FileListWs = ThisWorkbook.Worksheets("File List")
Set DestWs = ThisWorkbook.Worksheets("Database")
With FileListWs
TotFiles = Application.CountA(.[a:a])
If TotFiles > 0 Then
For Counter = 1 To TotFiles
coll.Add .Cells(Counter, 1), .Cells(Counter, 1)
Next
End If
End With
'look at folder
Set fso = CreateObject("Scripting.FileSystemObject")
'put full path to folder containing data files in the next line of code
Set fld = fso.GetFolder("C:\Documents and Settings\Patrick & Thuc-Nghi\My Documents\Patrick's\Excel files\CaptG\")
For Each fil In fld.Files
On Error Resume Next
coll.Add fil.Name, fil.Name
If Err <> 0 Then
'file already processed, do nothing
Err.Clear
Else
'not processed yet; process it
With FileListWs
If TotFiles = 0 Then
.[A2] = fil.Name
Else
'.Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0) = fil.Name
.Cells(65536, 1).End(xlUp).Offset(1, 0) = fil.Name
End If
End With
'see if it's already open
Set SourceWb = Workbooks(fil.Name)
If Err <> 0 Then
'was not open
WasOpen = False
Set SourceWb = Workbooks.Open(fil.Path)
Else
WasOpen = True
End If
Set SourceWs = SourceWb.Sheets(1)
With SourceWs
.Range(.Cells(2, "A"), .Cells(.Rows.Count, "A").End(xlUp).Offset(0, 14)).Copy _
DestWs.Cells(DestWs.Rows.Count, "A").End(xlUp).Offset(1, 0)
End With
errorflag = ""
If Not WasOpen Then SourceWb.Close False
End If
Next
Set coll = Nothing
Set fil = Nothing
Set fld = Nothing
Set fso = Nothing
Application.ScreenUpdating = True
MsgBox "Done"
End Sub
|