469,280 Members | 1,818 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,280 developers. It's quick & easy.

Parsing csv file in VB (example included)

I needed to parse a csv file for my project. Could not find any so I
put together this code. It works for general cases. Use it and let me
know. Just
Cut and paste the 2 functions in a new Form and the csv text in
test.csv in the same directory. Watch for the line breaks!

'------ Parse CSV + Demo ----------------------
' (c) Shahid Mahmood (ma*****@alum.rpi.edu)
' ---------------------------------------------
' Parses a csv file and prints results in a debug window
' If you know how many fields per line are coming, you can diemnsion
' 'strTemp() array accordingly and lost the ReDim ..()
' Handles the case of quoted and un-quoted fields, (only double quoted
' Also handles commas inside a quoted field. DOES not handle embedded
' quotes or single quoted fields.
' Enjoy!

Private Sub Form_Load()
Dim fieldArray() As String
Dim i As Integer
Dim lineRead As String
'MsgBox App.Path ' to see where VB is reading from
Open App.Path + "\" + "test.csv" For Input As #1

While Not EOF(1)
Line Input #1, lineRead
fieldArray = parseCsv(lineRead)
' Do whatever you want with the array of fields, e.g.
If lineRead <> "" Then For i = 0 To UBound(fieldArray):_
Debug.Print fieldArray(i): Next
End Sub

Function parseCsv(lineIn As String) As String()
Dim s As String
Dim local_s As String
Dim n1 As Integer
Dim n2 As Integer
Dim str2 As String
Dim i As Integer
Dim strTemp() As String
i = 0
s = Trim(lineIn) ' remove spaces, if any

While Len(s)
ReDim Preserve strTemp(i) ' Didnt want to have fixed fields,
' dont know how to dynamically allocate, hence ...
If Mid$(s, 1, 1) = """" Then ' if already in quotes ...
strTemp(i) = Mid$(s, 2, InStr(2, s, """") - 2)'find 2nd ""
If InStr(s, ",") Then strTemp(i) = Mid$(s, 1, InStr(s, ",") -
End If
's = Mid$(s, Len(strTemp(i)) + 1)
n2 = InStr(Len(strTemp(i)) Or 1, s, ",")
If n2 Then s = Trim(Mid$(s, n2 + 1)) Else s = "" ' clip till next
i = i + 1
parseCsv = strTemp
End Function
'---- END -------

Sample test.csv
"Hello, World", wow, " asdasd asdasd"
"Hello1, World1", wow1, " asdasd1 asdasd1"
"Hello2, World2", wow2, " asdasd2 asdasd2"
"This is Field1", "Field2",Field3,"Field4",field5,field6, "Field7,8,9"
Jul 17 '05 #1
0 23820

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

14 posts views Thread by Viktor Rosenfeld | last post: by
4 posts views Thread by ArmedCoder | last post: by
6 posts views Thread by Tuomas Rannikko | last post: by
4 posts views Thread by Rick Walsh | last post: by
9 posts views Thread by ankitdesai | last post: by
13 posts views Thread by Chris Carlen | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.