
Parsing CSV strings like "Doe, John",33, "6'2"""
Hi Dan,
Here is some code that I use. It is easily adaptable. Not sure if it is
the most efficient way but it works great.
***Note - I already knew the number of fields in my line. You should use
ReDim if lines vary.
Option Explicit
Dim OrderField(39) 'Known number of fields in line
Dim FieldCounter As Integer 'Counter for the array
Dim CurPos As Long 'Cursor position
Dim CurChar As String 'Current character
Dim txtStr As String 'String data
Dim NextQuote As Integer 'Next quote to determine string fields
Const StrQualifier = """" 'String qualifier
Const Delimiter = "," 'Delimiter
Function ParseOrderString(ByVal SrcStr As String) As Integer
txtStr = "" ' Used to build field data
FieldCounter = 1 ' Started my array at 1 to make some
later code easier
CurPos = 1 ' Start at the begining of the line
CurChar = Mid(SrcStr, CurPos, 1) ' Start at the first character
'Loop until the end of the comma delimited line
Do Until CurChar = ""
CurChar = Mid(SrcStr, CurPos, 1)
'Check to see if the current character is a quote
If CurChar = StrQualifier Then
'If current character is a quote find the position of the next quote
NextQuote = InStr(CurPos + 1, SrcStr, StrQualifier, 1)
'If the next character after the quote is a comma we have found
'the end of the field. Get the entire field
If Mid(SrcStr, NextQuote + 1, 1) = Delimiter Then
txtStr = Mid(SrcStr, CurPos + 1, NextQuote - CurPos - 1)
CurPos = NextQuote + 1
OrderField(FieldCounter) = txtStr
'Increase the array counter
FieldCounter = FieldCounter + 1
'Set the txtStr to an empty string
txtStr = ""
Else
End If
Else
'We have hit the comma, store the data in the OrderField array
If CurChar = Delimiter Then
'Store the data in txtStr in the array
OrderField(FieldCounter) = txtStr
'Increase the array counter
FieldCounter = FieldCounter + 1
'Set the txtStr to an empty string
txtStr = ""
Else
'Build the txtStr string until we hit the next comma
txtStr = txtStr & CurChar
End If
End If
'Move the cursor to the next position
CurPos = CurPos + 1
Loop
End Function
Hope this helps!
Robert Whetzel
***************
Hello fellow VBers!
I needed to parse strings containing a comma delimited variables (quotes
around strings).
For example, to convert a string like:
"Doe, John",33, "6'2"""
into an array, such that:
Arr(0)= Doe, John
Arr(1)= 33
Arr(2)= 6'2"
Ok, so I wrote a procedure that does this, and it works. But, the
procedure is huge, slow and very ugly.
It's so ugly that I feel that I'm overlooking a simpler way to do this.
I am wondering if any other coders would care to suggest such a technique?