Sub ImportWorkbooks()
Dim FilesToProcess As Integer
Dim i As Integer
Dim bArchiveFiles As Boolean
Dim sFileName As String
Dim sOutFile As String
Dim rwLast As Long
Dim Sht As Worksheet
Const TOP_FOLDER = "H:\Test" 'adjust folder name to suit
Const ARCHIVE_FOLDER = "H:\Test\Imported" 'adjust folder name to suit
Const PATH_DELIM = "\"
'set to False if you DON'T want to move imported files to new folder
bArchiveFiles = True
'the FileSearch object lets you search a folder and, optionally its subfolders,
'for files of a defined type. It loads the names of all found files into an array,
'which we can use to import those files.
With Application.FileSearch
.NewSearch
.LookIn = TOP_FOLDER
.SearchSubFolders = False 'we only want to search the top folder
.Filename = "*.xls" 'change this to suit your needs
.Execute
FilesToProcess = .FoundFiles.Count
'check that files have been located. If not, display message and exit routine.
If FilesToProcess = 0 Then
MsgBox "No files found, nothing processed", vbExclamation
Exit Sub
End If
Set Sht = ActiveSheet
For i = 1 To FilesToProcess
'find the last used row
rwLast = Sht.Cells(Rows.Count, 1).End(xlUp).Row + 1
'if sheet is blank we want to import the headings as well
If rwLast = 2 Then rwLast = 1
'import each file, then close without saving
Workbooks.Open .FoundFiles(i)
If rwLast > 1 Then
Range("A1").CurrentRegion.Offset(1, 0).Copy _
Destination:=Sht.Cells(rwLast, 1)
Else
Range("A1").CurrentRegion.Copy _
Destination:=Sht.Cells(rwLast, 1)
End If
Workbooks(.FoundFiles(i)).Close savechanges:=False
'archive the imported files
If bArchiveFiles Then
'code for archiving imported files...
sFileName = StrRev(Left(.FoundFiles(i), Len(.FoundFiles(i)) - 4))
sFileName = Left(sFileName, InStr(1, sFileName, PATH_DELIM) - 1)
sFileName = StrRev(sFileName)
sOutFile = ARCHIVE_FOLDER & PATH_DELIM & sFileName & " " _
& Format(Date, "yyyymmdd") & ".csv"
FileCopy .FoundFiles(i), sOutFile
Kill .FoundFiles(i)
End If
Next i
End With
End Sub
'The StrRev function reverses a text string. We are using it here to simplify
'extracting the file name: once the full path is reversed, we can pull out everything
'to the left of the first path delimiter. Reversing this string gives us the file name.
'Note: VBA has a StrReverse function that you can use instead of this custom function.
Function StrRev(sData As String) As String
Dim i As Integer
Dim sOut As String
sOut = ""
For i = 1 To Len(sData)
sOut = Mid(sData, i, 1) & sOut
Next i
StrRev = sOut
End Function