Load csv file into a VBA array rather than Excel Sheet

前端 未结 6 1106
半阙折子戏
半阙折子戏 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:22

    To get a known format csv data file into a 2D array I finally adopted the following method, which seems to work well and is quite quick. I decided that file read operations are fairly fast nowadays, so I run a first pass on the csv file to get the size required for both dimension of the array. With the array suitably dimensioned it is then a simple task to re-read the file, line by line, and populate the array.

    Function ImportTestData(ByRef srcFile As String, _
                            ByRef dataArr As Variant) _
                            As Boolean
    
    Dim FSO As FileSystemObject, Fo As TextStream
    Dim line As String, Arr As Variant
    Dim lc As Long, cc As Long
    Dim i As Long, j As Long
    
    ImportTestData = False
    Set FSO = CreateObject("Scripting.FilesystemObject")
    Set Fo = FSO.OpenTextFile(srcFile)
    
    ' First pass; read the file to get array size
    lc = 0 ' Counter for number of lines in the file
    cc = 0 ' Counter for number of columns in the file
    While Not Fo.AtEndOfStream  ' Read the csv file line by line
        line = Fo.ReadLine
        If lc = 0 Then ' Count commas to get array's 2nd dim index
            cc = 1 + Len(line) - Len(Replace(line, ",", ""))
        End If
        lc = lc + 1
    Wend
    Fo.Close
    
    ' Set array dimensions to accept file contents
    ReDim dataArr(0 To lc - 1, 0 To cc - 1)
    'Debug.Print "CSV has "; n; " rows with "; lc; " fields/row"
    If lc > 1 And cc > 1 Then
        ImportTestData = True
    End If
    
    ' Second pass; Re-open data file and copy to array
    Set Fo = FSO.OpenTextFile(srcFile)
    lc = 0
    While Not Fo.AtEndOfStream
        line = Fo.ReadLine
        Arr = Split(line, ",")
        For i = 0 To UBound(Arr)
            dataArr(lc, i) = Arr(i)
        Next i
        lc = lc + 1
    Wend
    
    End Function   'ImportTestData()
    

    I created this as a Function rather than a Sub to get a simple return value, if required. Reading a file with 8,500 rows of 20 columns takes approximately 180ms.
    This method assumes that the structure (number of delimiters) of the CSV file is the same for every row, typical of a data logging application.

提交回复
热议问题