I needed a CSV parser as the PB Parse() function doesn't handle quoted strings so I put this together.
It seems to work okay but I'd be glad to hear about improvements or bugs. If a comma is in quotation marks it should be ignored. I looked around for a CSV spec to find out if tabs should be treated special but I couldn't find anything, feel free to post a URL of a spec that may help me standardise this.
------------------
Paul Dwyer
Network Engineer
Aussie in Tokyo
(Paul282 at VB-World)
It seems to work okay but I'd be glad to hear about improvements or bugs. If a comma is in quotation marks it should be ignored. I looked around for a CSV spec to find out if tabs should be treated special but I couldn't find anything, feel free to post a URL of a spec that may help me standardise this.
Code:
#Include "win32api.inc" Declare Function CSV$(CSV_line As String, Column As Word) As String ' CSV Parser Include file, used as the Parse$() command in PB except it will recognise quotation marks Function CSV$(CSV_line As String, Column As Word) As String Dim CSV_Text As String Dim i As Long Dim InQuote As Integer Dim CurrentCol As Integer Dim StartFound As Integer Dim StartChr As Long Dim ReturnLen As Long InQuote = %False CurrentCol = 1 StartFound = %False ReturnLen = 0 ' Catch from Beginning if Column = 1 If Column = 1 Then StartFound = %true StartChr = 0 End If 'strip code to first $crlf If Instr(1,CSV_Line,$crlf) Then CSV_Text = Left$(CSV_Line, Instr(1,CSV_Line,$crlf)) Else CSV_Text = CSV_Line & Chr$(0) End If 'pass string left to right For i = 1 To Len(CSV_Text) If CurrentCol = Column Then Incr ReturnLen 'Increment length of Cell Select Case Mid$(CSV_Text,i,1) Case """" 'Entering or Exiting a quoted field or section of field If InQuote = %True Then InQuote = %false Else InQuote = %True End If Case "," If InQuote = %True Then ' ignore Else If CurrentCol = Column Then 'end of cell found Exit For End If If CurrentCol = Column -1 Then 'Beginning of Cell Found StartChr = i 'Mark Beginning of Cell StartFound = %true End If If CurrentCol < Column Then Incr CurrentCol End If End Select Next If StartFound = %True Then 'String pass is done, was the column found? If ReturnLen = 1 Then CSV$ = "" 'zero length cell, two comma's together Else CSV$ = Mid$(CSV_Text,StartChr + 1, ReturnLen -1 ) End If Else CSV$ = "" 'error, field doesn't exist End If End Function
Paul Dwyer
Network Engineer
Aussie in Tokyo
(Paul282 at VB-World)
Comment