I am splitting up a comma delimited CSV-file by using
this code below. It works fine, but some of the records in
the file contains a comma within the data, even though comma is reserved
as the delimiter. For example a record contains a description text where the user
has entered commas and my script enterprets that like the record ends.
How can I somehow get over that?
Here’s an example of a line in my CSV-file. Please remark the empty records at the end of the lines can be witout the “” enclosing characters:
“1”,”34353434″,”Adam”,”Traxx”,”343″,”This man is the boss, please handle with respect”,””,,””,””,,”,””,”0″,,”
This is how I read and split:
Sub ReadOnlineExample()
Dim line_read As String
Dim tempfilename As String
Dim i As Integer
Dim rows_skipped As Integer
Dim line_split(0 To 125) As String
Dim MortalityRates(0 To 125) As Double
tempfilename = "C:\MortalityRateTable.csv"
Dim sr As New System.IO.StreamReader(tempfilename)
'Split the line into individual data
line_split = line_read.Split(",")
'Save the split data into an array
For i = 0 To UBound(line_split)
MortalityRates(i) = line_split(i)
Next i
End Sub
Can anyone help? Maybe it’s just a simple solution I just can’t see 🙂
Use a proper CSV parser – File Helpers is a popular option.
There is also a parser from Microsoft – in the
Microsoft.VisualBasic.FileIOnamespace, theTextFieldParser.These take care of the subtle aspects of CSV that most hand rolled solutions don’t consider until hitting an issue.