Hi,
I am totally new to using VBA in Excel and need your help. Thanks in advance!
I have a folder with multiple .csv files which I need to merge into one excel worksheet.
The file details are as follows:
- Each file contains two columns of data, the first column is identical in all .csv files. I only need the data from the second columns.
- all data should be in one data sheet.
- above each column of data (corresponding to second columns in starting .csv files) should be placed the file name from which that data originates.
- all starting .csv files are in one folder
Here is the illustration what I expect to achieve:

I found a macros on this website (see below) which almost does what I want, except for putting the names of the starting files in the row 1. What do I need to add it that it also records the file names in the column? Also, when there are multiple files in
the folder, which order does the VBA follow in picking .csv files: is it based on the file name or the data it has been created? Huge thanks in advance!
I would greatly appreciate your help,
Kind regards,
Sub GetFromCSVs()
Dim WB As Workbook
Dim R As Range
Dim bFirst As Boolean
Dim stFile As String
Dim stPath As String
stPath = "C:\Temp\CSVs" ' change the path to suit
stFile = Dir(stPath & "*.csv")
bFirst = True
Set R = Workbooks.Add(xlWorksheet).Sheets(1).Range("A1")
Do Until stFile = ""
Set WB = Workbooks.Open(stPath & stFile, ReadOnly:=True)
If bFirst Then
WB.Sheets(1).Range("A1").CurrentRegion.Copy Destination:=R
Set R = R.Offset(, 2)
bFirst = False
Else
WB.Sheets(1).Range("A1").CurrentRegion.Columns(2).Copy Destination:=R
Set R = R.Offset(, 1)
End If
WB.Close saveChanges:=False
stFile = Dir() ' next file
Loop
End Sub