Load csv file into a VBA array rather than Excel Sheet

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

    Yes read it as a text file.

    See this example

    Option Explicit
    
    Sub Sample()
        Dim MyData As String, strData() As String
    
        Open "C:\MyFile.CSV" For Binary As #1
        MyData = Space$(LOF(1))
        Get #1, , MyData
        Close #1
        strData() = Split(MyData, vbCrLf)
    End Sub
    

    FOLLOWUP

    Like I mentioned below in the comments, AFAIK, there is no direct way of filling a 2d Array from a csv. You will have to use the code that I gave above and then split it per line and finally filling up a 2D array which can be cumbersome. Filling up a column is easy but if you specifically want say from Row 5 to Col 7 Data then it becomes cumbersome as you will have to check if there are sufficient columns/rows in the data. Here is a basic example to get Col B in a 2D Array.

    NOTE: I have not done any error handling. I am sure you can take care of that.

    Let's say our CSV File looks likes this.

    enter image description here

    When you run this code

    Option Explicit
    
    Const Delim As String = ","
    
    Sub Sample()
        Dim MyData As String, strData() As String, TmpAr() As String
        Dim TwoDArray() As String
        Dim i As Long, n As Long
    
        Open "C:\Users\Siddharth Rout\Desktop\Sample.CSV" For Binary As #1
        MyData = Space$(LOF(1))
        Get #1, , MyData
        Close #1
        strData() = Split(MyData, vbCrLf)
    
        n = 0
    
        For i = LBound(strData) To UBound(strData)
            If Len(Trim(strData(i))) <> 0 Then
                TmpAr = Split(strData(i), Delim)
                n = n + 1
                ReDim Preserve TwoDArray(1, 1 To n)
                '~~> TmpAr(1) : 1 for Col B, 0 would be A
                TwoDArray(1, n) = TmpAr(1)
            End If
        Next i
    
        For i = 1 To n
            Debug.Print TwoDArray(1, i)
        Next i
    End Sub
    

    You will get the output as shown below

    enter image description here

    BTW, I am curious that since you are doing this in Excel, why not use inbuilt Workbooks.Open or QueryTables method and then read the range into a 2D array? That would be much simpler...

提交回复
热议问题