Dear all
I have a bunch of data in many different .CSV files that I am trying to combine into a single .xls file using a macro. Each .CSV file have a unique name representing the data source and consists of 3 columns: A) timestamp, B) logged/recorded value, and C) Unit (i.e. Volts)
Now to the part that gives me trouble: I would like to create a single .XLS file that contains all the data from the different .CSV files added in consecutive columns. And with the .CSV filename added to an inserted first/top row.
I have found and modified two different macros that will either combine the data into a single .XLS file (sheet) or inset a header for each dataset in the first row of a . XLS sheet, but I have no idea how to make both macros work together as one.
Here is my first macro that adds filenames above each dataset:
Option Explicit
Sub ImportCSVsWithReference()
Dim wbCSV As Workbook
Dim wsMstr As Worksheet: Set wsMstr = ThisWorkbook.Sheets("Ark1")
Dim fPath As String: fPath = "Y:\AnyPathWithCSVfiles\"
Dim fCSV As String
Dim NextCol As Long
If MsgBox("Delete exsisting data?", _
vbYesNo, "Delete exsisting data before import?") = vbYes Then
wsMstr.UsedRange.Clear
NextCol = 1
Else
NextCol = wsMstr.Cells(3, Columns.Count).End(xlToLeft).Column + 1
End If
Application.ScreenUpdating = False 'Speeds up the macro
fCSV = Dir(fPath & "*.csv") 'start the CSV file listing
Do While Len(fCSV) > 0
'open a CSV file
Set wbCSV = Workbooks.Open(fPath & fCSV)
'Adding a first row containing the filename
Range("A1") = Left(ActiveWorkbook.Name, InStr(ActiveWorkbook.Name, ".csv") - 1)
'Copy source and closes source
ActiveSheet.UsedRange.Copy wsMstr.Cells(1, NextCol)
wbCSV.Close False
'ready next CSV
fCSV = Dir
NextCol = wsMstr.Cells(3, Columns.Count).End(xlToLeft).Column + 3 'Adding columns for the data
Loop
Application.ScreenUpdating = True
End Sub
My next little macro that combines the .CSV files into a single .XLS file looks like this:
Sub import()
Dim Str1 As String
Dim i As Integer
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = True
.Filters.Clear
.Filters.Add "Excel Files (*.xls)", "*.xls"
.Filters.Add "All Files (*.*)", "*.*"
.Show
If .SelectedItems.Count > 0 Then
Worksheets(1).Activate
For i = 1 To .SelectedItems.Count
Str1 = "TEXT;" & .SelectedItems.Item(i)
With ActiveSheet.QueryTables.Add(Connection:=Str1, Destination:=Cells(1, 3 * i))
.TextFileSemicolonDelimiter = True
.TextFileDecimalSeparator = "."
.TextFileThousandsSeparator = ","
.Refresh BackgroundQuery:=False
End With
Next
End If
End With
End Sub
I sorry if my syntax if offensive or cluttered, but I hope it makes sense?
Best regards, Emil
Bookmarks