Hi! My code is given below. I am able to combine multiple csv files but struggling for two things:
1. Sorting the data before the final output.
2. Deleting unwanted data of specific dates before the final output. (T
I am also attaching 3 sample csv files for your reference.
The first column DisplayDate is in 'dd-mm-yyyy hh:mm:ss' format
example : 20-03-2023 09:15:00 (20th March 2023)
Desired result
* The final csv file has dates sorted from newest to oldest. I want it the other way round - oldest to newest
* Identify max date and delete all records which are not equal to max date. Out of the multiple csv files, there will be very few files which will have more than one date. If that is the case, keep data of max (newest) date and remove records of old dates.
This code may not be efficient and perfect but it works. Please help me modify this code as per my desired result and if possible increase its efficiency and speed. Thank you
Sub MergeCSVFiles()
Dim folderPath As String
Dim csvFileName As String
Dim csvContent As String
Dim finalContent As String
Dim fso As Object
Dim folder As Object
Dim file As Object
Dim csvData As Variant
Dim lastRow As Long
Dim lastColumn As Long
Dim currentRow As Long
Dim headerAdded As Boolean
folderPath = "C:\Users\USER\Desktop\bsv\"
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(folderPath)
For Each file In folder.Files
If Right(file.Name, 4) = ".csv" And LCase(file.Name) <> "merged.csv" Then ' Check if file is CSV and not merged.csv
csvFileName = file.Name
' I am extracting desired word from filename
Dim fileNameParts As Variant
fileNameParts = Split(csvFileName, "_")
Dim stockName As String
If UBound(fileNameParts) >= 1 Then
stockName = fileNameParts(1)
Else
stockName = ""
End If
' Opening file and reading content
Open folderPath & csvFileName For Input As #1
csvContent = Input(LOF(1), 1)
Close #1
' Adding filename to content
csvData = Split(csvContent, vbCrLf)
lastRow = UBound(csvData) - 1 ' Last row index
lastColumn = UBound(Split(csvData(0), ",")) ' Last column index
If Not headerAdded Then
csvData(0) = csvData(0) & ",Stock" ' Adding filename header to last column
headerAdded = True
End If
For currentRow = 1 To lastRow - 1
csvData(currentRow) = csvData(currentRow) & "," & stockName ' Adding stock name to last column
Next currentRow
csvData(lastRow) = csvData(lastRow) & "," & stockName ' Adding stock name to last record
csvContent = Join(csvData, vbCrLf)
' Appending content to final CSV
If finalContent = "" Then
finalContent = csvContent ' Adding header row
Else
'finalContent = finalContent & vbCrLf & csvContent ' Adding content rows
finalContent = finalContent & csvContent ' Adding content rows
End If
End If
Next file
Open folderPath & "merged.csv" For Output As #2
Print #2, finalContent
Close #2
MsgBox "All CSV files merged"
End Sub
Bookmarks