I have the following code that aims to convert multiple csv files into a single array in VBA. The code works perfectly except for the one part.
This works just fine:
Sub CreateArrayFromCSV()
Dim cn As ADODB.Connection, RS As ADODB.Recordset, strSQL As String
Dim rsArr As Variant, dataArr As Variant, yearArr As Variant
Dim i As Long, j As Long
strPath = "path"
Set cn = CreateObject("ADODB.Connection")
strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strPath & ";Extended Properties=""text;HDR=No;FMT=TabDelimited"";"
cn.Open strcon
This is now the part that makes trouble:
strSQL = vbNullString
For i = 2012 To 2014
If strSQL <> vbNullString Then strSQL = strSQL & " UNION ALL "
strSQL = strSQL & "SELECT *, " & i & " as Jahr FROM Data_" & i & ".txt"
Next i
strSQL = strSQL & ";"
Debug.Print strSQL
Set RS = cn.Execute(strSQL)
rsArr = Application.WorksheetFunction.Transpose(RS.GetRows)
RS.Close
To be precise, the trouble is only in that line:
strSQL = strSQL & "SELECT *, " & i & " as Jahr FROM Data_" & i & ".txt"
I want to add a column to the Select *
, because I don't have headers in the .csv file. The solution could be two-fold, either:
- What are the column names? I've tried col1
and Column 1
, no avail.
- How can I add a column to the Select *
?
This works just fine again:
ReDim dataArr(1 To (UBound(rsArr)) / 2, 1 To 3)
For j = LBound(rsArr) To UBound(rsArr) Step 2
yearArr = Split(rsArr(j + 1, 1), vbTab)
dataArr(1 + Int(j / 2), 1) = Left(rsArr(j, 1), 5) * 1
dataArr(1 + Int(j / 2), 2) = yearArr(14)
dataArr(1 + Int(j / 2), 3) = i
Next j
Set cn = Nothing
End Sub