Option Explicit
Sub CombineCSVFiles()
Dim sCSV$, sCombCSV$, iFF%
Dim myFolder, myFile, arrCSV
Dim myRange As Range
Dim fso As Object
Dim fPath As String
' Turn off some Excel functionality so your code runs faster
With Application
.ScreenUpdating = False
.DisplayStatusBar = False
.EnableEvents = False
.Calculation = xlCalculationManual
End With
' Use File System Object to choose folder with files
Set fso = CreateObject("Scripting.FileSystemObject")
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
.InitialFileName = ThisWorkbook.Path & "\" ' Default path - Change as required
.Title = "Please Select a Folder"
.ButtonName = "Select Folder"
If .SelectedItems.Count > 0 Then fPath = .SelectedItems(1) & "\" Else Exit Sub
End With
' Open each file consequently and merge into a variable
iFF = FreeFile
Set myFolder = fso.GetFolder(fPath).Files
For Each myFile In myFolder
If LCase(myFile) Like "*.csv" Then
sCSV = Space(FileLen(myFile))
Open myFile For Binary Access Read As #iFF
Get #iFF, , sCSV
sCombCSV = sCombCSV & sCSV
Close #iFF
End If
' Loop through all files in folder
Next myFile
' Convert variable to array
arrCSV = Split(sCombCSV, vbCrLf)
' Paste data back to Excel
Set myRange = Range(Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1), Range("A" & Rows.Count).End(xlUp).Offset(UBound(arrCSV) + 1))
myRange = Application.Transpose(arrCSV)
myRange.TextToColumns DataType:=xlDelimited, ConsecutiveDelimiter:=False, Comma:=True
' clean up
myFile = vbNullString
iFF = 1
' Turn Excel functionality back on
With Application
.DisplayStatusBar = True
.EnableEvents = True
.Calculation = xlCalculationAutomatic
End With
End Sub
Bookmarks