added an error handling - 1534001 - has 59 initial records of ? . MS (jet) uses the first 10 records to judge the field type so in this instance it thinks it is a text field - hence the issue. There are other fancier ways of adjusting like adjusting the registry so jet looks at the whole column but this is fast and good enough
Sub LoadCSVtoArray()
On Error GoTo 0
Dim stFilename() As Variant
Dim stFilenamez As String
Dim a As Integer
Dim StrSQLcorr As String
stFilename() = Application.GetOpenFilename("Csv Files (*.csv), *.Csv", , "Open the .csv file to merge", , True)
For a = 1 To UBound(stFilename())
strfilenamez = Split(stFilename(a), "\")(UBound(Split(stFilename(a), "\")))
strPath = Replace(stFilename(a), strfilenamez, "", 1)
Set cn = CreateObject("ADODB.Connection")
strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strPath & ";Extended Properties=""text;HDR=Yes;FMT=Delimited"";"
cn.Open strcon
strsql = "transform Sum([Value]) SELECT id, Year, Day FROM " & strfilenamez & " GROUP BY id, Year, Day PIVOT Month;"
On Error GoTo 0
Dim rs As Recordset
Dim rsARR() As Variant
Dim fldCount As Integer
Dim iCol As Integer
Dim iRow As Integer
On Error GoTo errorh:
Set rs = cn.Execute(strsql)
On Error GoTo 0
rsARR = rs.GetRows
fldCount = rs.Fields.Count
For iCol = 1 To fldCount
Range("a1").Cells(1, iCol).Value = rs.Fields(iCol - 1).Name
Next
rs.Close
Set cn = Nothing
Cells(GetLastRow("Sheet1", "A") + 1, 1).Resize(UBound(rsARR, 2) + 1, UBound(rsARR, 1) + 1).Value = TransposeDim(rsARR)
Next a
Exit Sub
errorh:
strsql = "transform Sum([Value]) SELECT id, Year, Day FROM " & strfilenamez & " Where (value <> '?') GROUP BY id, Year, Day PIVOT Month;"
Resume
End Sub
Function TransposeDim(v As Variant) As Variant
' Custom Function to Transpose a 0-based array (v)
Dim X As Long, Y As Long, Xupper As Long, Yupper As Long
Dim tempArray As Variant
Xupper = UBound(v, 2)
Yupper = UBound(v, 1)
ReDim tempArray(Xupper, Yupper)
For X = 0 To Xupper
For Y = 0 To Yupper
tempArray(X, Y) = v(Y, X)
Next Y
Next X
TransposeDim = tempArray
End Function
Function GetLastRow(strSheet, strColum) As Long
Dim MyRange As Range
Dim lngLastRow As Long
Set MyRange = Worksheets(strSheet).Range(strColum & "1")
lngLastRow = Cells(1048576, MyRange.Column).End(xlUp).Row
GetLastRow = lngLastRow
Set MyRange = Nothing
End Function
Bookmarks