Created
July 2, 2015 09:57
-
-
Save x1alpha76/6b7f4c0af8a43f1fff76 to your computer and use it in GitHub Desktop.
Visual Basic Script function for reading CSV strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Quotation marks are not removed from the final element.
To solve this issue, I modified line 62 to the following: