Skip to content

Instantly share code, notes, and snippets.

@x1alpha76
Created July 2, 2015 09:57
Show Gist options
  • Save x1alpha76/6b7f4c0af8a43f1fff76 to your computer and use it in GitHub Desktop.
Save x1alpha76/6b7f4c0af8a43f1fff76 to your computer and use it in GitHub Desktop.
Visual Basic Script function for reading CSV strings
'Does not support multiline
'
'Example usage
'Const ForReading = 1
'Set objFSO = CreateObject("Scripting.FileSystemObject")
'Set objFile = objFSO.OpenTextFile("test.csv", ForReading)
'Do Until objFile.AtEndOfStream
' fields = ReadCSV(objFile.ReadLine)
' WScript.Echo fields(0)
'Loop
'objFile.Close
Public Function ReadCSV(row)
Dim data()
size = 5
ReDim data(size)
offset = 0
nextComma = InStr(row,",")
nextQuote = InStr(row,"""")
index = 0
Do While NOT IsNull(nextComma) AND nextComma > 0
If nextQuote = 0 OR nextComma < nextQuote Then
if offset = 0 Then
val = Left(row, nextComma-1)
Else
val = Mid(row, offset, nextComma-offset)
End If
val = trim(val)
offset = nextComma + 1
nextComma = InStr(offset, row,",")
else
offset = nextQuote +1
nextQuote = InStr(offset, row,"""")
Do While NOT IsNull(nextQuote) AND nextQuote > 0 AND Mid(row, nextQuote, 2) = """"""
nextQuote = InStr(nextQuote+2,row,"""")
Loop
If nextQuote = 0 Then
Wscript.Echo "CSV is malformed or multiline (not supported)"
End If
val = Replace(Mid(row, offset, nextQuote-offset),"""""","""")
offset = InStr(nextQuote,row,",") + 1
nextQuote = InStr(offset, row,"""")
nextComma = InStr(offset,row,",")
End If
data(index) = val
index = index + 1
if size < index then
size = size + 5
ReDim Preserve data(size)
End If
Loop
val = right(row, Len(row)-offset +1)
data(index) = val
index = index + 1
ReDim Preserve data(index)
ReadCSV = data
End Function
@cmw72
Copy link

cmw72 commented Aug 6, 2015

Quotation marks are not removed from the final element.

To solve this issue, I modified line 62 to the following:

    val = Replace( Right( row, Len( row ) - offset + 1 ), """", "" )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment