How to Read a .CSV File Into An Array

S

Steve Roberts

Anyone have a good example of how to read the contents of a .CSV file into a
dynamic array?

I have a file c:\users.csv that contains 3 columns TeamName, UserName,
Location I need to read the information into a Dynamic Array.

I guess there are 2 parts 1 is how to read the contents of the file and the
other is putting the information into the array.

Thanks for your help.

Steve
 
D

devlei

I am only a beginner, but had to do a similar thing. Try this

Sub TestCSV()
Dim fs, A
Dim retstring As String
Dim I, intCounter As Integer
Dim arrUsers(), arr() As String

'First determine number of items in file in order to ReDim array
Set fs = CreateObject("Scripting.FileSystemObject")
Set A = fs.OpenTextFile("c:\users.csv", 1)
Do While A.AtEndOfStream <> True
retstring = A.ReadLine
intCounter = intCounter + 1
Loop
A.Close

'Now fill your Dynamic Array from the CSV file
'Split and Trim functions are used for text manipulations
ReDim arrUsers(intCounter, 2)
Set fs = CreateObject("Scripting.FileSystemObject")
Set A = fs.OpenTextFile("c:\users.csv", 1)
For I = 0 To intCounter - 1
retstring = A.ReadLine
arr() = Split(retstring, ",")
arrUsers(I, 0) = Trim(arr(0))
arrUsers(I, 1) = Trim(arr(1))
arrUsers(I, 2) = Trim(arr(2))
Next
A.Close

'You should now be able to use your array

End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top