[FONT=Courier New]Option Explicit[/FONT]
[FONT=Courier New][/FONT]
[FONT=Courier New]Const WORKSHEET_NAME As String = "Sheet1" [COLOR=green]' the name of the worksheet if you want stats[/COLOR][/FONT]
[FONT=Courier New][/FONT]
[FONT=Courier New]Public Sub CombineMultipleFiles()[/FONT]
[FONT=Courier New][/FONT]
[FONT=Courier New] Dim ws As Worksheet
Dim sFileArray As Variant
Dim sFile As Variant
Dim sOutFile As Variant
Dim sFileCount As Integer
Dim inFH As Integer
Dim outFH As Integer
Dim sRecord As String
Dim iLineCount As Long
Dim iRow As Integer
Dim dtStart As Date
sFileArray = Application.GetOpenFilename( _
FileFilter:="CSV files (*.csv), *.csv, Text files (*.txt), *.txt, " _
& "VBA files (*.bas; *.cls), *.bas; *.cls, " _
& "All files (*.*), *.*", _
FilterIndex:=1, MultiSelect:=True, Title:="Select files to open:-")
If Not IsArray(sFileArray) Then Exit Sub
sFileCount = UBound(sFileArray) - LBound(sFileArray) + 1
If UBound(sFileArray) = LBound(sFileArray) Then
MsgBox "You have only selected one input file!" & Space(10), vbOKOnly + vbExclamation
Exit Sub
End If
sOutFile = Application.GetSaveAsFilename( _
FileFilter:="CSV files (*.csv), *.csv, Text files (*.txt), *.txt", _
Title:="Select output file:-")
If sOutFile = "False" Then Exit Sub
If Dir(sOutFile) <> "" Then Kill sOutFile
dtStart = Now()
If WORKSHEET_NAME <> "" Then Set ws = ThisWorkbook.Sheets(WORKSHEET_NAME)
Close
outFH = FreeFile()
Open sOutFile For Append As #outFH
ws.Columns("A:B").ClearContents
ws.Columns("A:B").Font.Bold = False
If WORKSHEET_NAME <> "" Then
With ws
.Range("A1") = "Filename"
.Range("B1") = "Records"
.Range("B1").NumberFormat = "#,##0"
.Range("A1:B1").Font.Bold = True
End With
End If
iRow = 1
For Each sFile In sFileArray
inFH = FreeFile()
Open sFile For Input As #inFH
iLineCount = 0
Do Until EOF(inFH)
Line Input #inFH, sRecord
Print #outFH, sRecord
iLineCount = iLineCount + 1
Loop
Close #inFH
iRow = iRow + 1
If WORKSHEET_NAME <> "" Then
With ws
.Cells(iRow, 1) = sFile
.Cells(iRow, 2) = iLineCount
ActiveWindow.ScrollRow = IIf(iRow <= 20, 1, iRow - 20)
End With
End If
Next sFile
Close #outFH
If WORKSHEET_NAME <> "" Then
With ws
.Cells(iRow + 1, 1) = "Total"
.Cells(iRow + 1, 1).Font.Bold = True
.Cells(iRow + 1, 2) = "=SUM(B2:B" & CStr(iRow) & ")"
.Cells(iRow + 1, 2).Font.Bold = True
End With
End If
MsgBox "Finished: " & CStr(sFileCount) & " files combined." & Space(10) & vbCrLf & vbCrLf _
& "Output file: " & sOutFile & Space(10) & vbCrLf & vbCrLf _
& "Run time: " & Format(Now() - dtStart, "hh:nn:ss") & Space(10), vbOKOnly + vbInformation
ActiveWindow.ScrollRow = 1
End Sub[/FONT]