Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleRead a CSV file into an array
Description
KeywordsCSV, comma-separated value, file, data, array
CategoriesFiles and Directories, Tips and Tricks
 
Grab the whole file into a string. Then use Split to break it into lines. For each line, use Split again to break it into fields.
 
Private Sub cmdGo_Click()
Dim file_name As String
Dim fnum As Integer
Dim whole_file As String
Dim lines As Variant
Dim one_line As Variant
Dim num_rows As Long
Dim num_cols As Long
Dim the_array() As String
Dim R As Long
Dim C As Long

    file_name = App.Path
    If Right$(file_name, 1) <> "\" Then file_name = _
        file_name & "\"
    file_name = file_name & "test.csv"

    ' Load the file.
    fnum = FreeFile
    Open file_name For Input As fnum
    whole_file = Input$(LOF(fnum), #fnum)
    Close fnum

    ' Break the file into lines.
    lines = Split(whole_file, vbCrLf)

    ' Dimension the array.
    num_rows = UBound(lines)
    one_line = Split(lines(0), ",")
    num_cols = UBound(one_line)
    ReDim the_array(num_rows, num_cols)

    ' Copy the data into the array.
    For R = 0 To num_rows
        If Len(lines(R)) > 0 Then
            one_line = Split(lines(R), ",")
            For C = 0 To num_cols
                the_array(R, C) = one_line(C)
            Next C
        End If
    Next R

    ' Prove we have the data loaded.
    For R = 0 To num_rows
        For C = 0 To num_cols
            Debug.Print the_array(R, C) & "|";
        Next C
        Debug.Print
    Next R
    Debug.Print "======="
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated