Load csv file into a VBA array rather than Excel Sheet

前端 未结 6 1119
半阙折子戏
半阙折子戏 2020-11-28 07:25

I am currently able to enter csv file data into Excel VBA by uploading the data via the code below then handling the table, surely not the best way as I am only interested i

6条回答
  •  囚心锁ツ
    2020-11-28 08:01

    OK, after looking into this, the solution I have arived at is to use ADODB (requires reference to ActiveX Data Objects, this loads the csv file into array without cycling the rows columns. Does require the data to be in good condition.

    Sub LoadCSVtoArray()
    
    strPath = ThisWorkbook.Path & "\"
    
    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 = "SELECT * FROM SAMPLE.csv;"
    
    Dim rs As Recordset
    Dim rsARR() As Variant
    
    Set rs = cn.Execute(strSQL)
    rsARR = WorksheetFunction.Transpose(rs.GetRows)
    rs.Close
    Set cn = Nothing
    
    [a1].Resize(UBound(rsARR), UBound(Application.Transpose(rsARR))) = rsARR
    
    End Sub
    

提交回复
热议问题