Richard
Wed Oct 11 07:59:12 CDT 2006
Here is a VBScript program by Michael Harris that parses a comma delimited
line from a csv file into an array of field values. If someone has a simpler
way, that works and does not use VB or ADO, great. Watch line wrapping:
==========
Option Explicit
Dim TestString
Dim strItem
TestString = "0000-000000-00000,SURNAME,FIRSTNAME,W,DATA FIELD
1,8/03/2006,DATA FIELD 2,DATA FIELD 3,AAAAAA/BBBBBB,DATA FIELD 5,52.81,0"
For Each strItem In CSVParse(TestString)
Wscript.Echo strItem
Next
TestString = """last, first"",flast,""another value"",3,still
another,""String, """"sample"""" is simple"",""String
""""Example,1"""""",Final"
For Each strItem In CSVParse(TestString)
Wscript.Echo strItem
Next
Function CSVParse(ByVal strLine)
' Function to parse comma delimited line and return array
' of field values.
Dim arrFields
Dim blnIgnore
Dim intFieldCount
Dim intCursor
Dim intStart
Dim strChar
Dim strValue
Const QUOTE = """"
Const QUOTE2 = """"""
' Check for empty string and return empty array.
If (Len(Trim(strLine)) = 0) then
CSVParse = Array()
Exit Function
End If
' Initialize.
blnIgnore = False
intFieldCount = 0
intStart = 1
arrFields = Array()
' Add "," to delimit the last field.
strLine = strLine & ","
' Walk the string.
For intCursor = 1 To Len(strLine)
' Get a character.
strChar = Mid(strLine, intCursor, 1)
Select Case strChar
Case QUOTE
' Toggle the ignore flag.
blnIgnore = Not blnIgnore
Case ","
If Not blnIgnore Then
' Add element to the array.
ReDim Preserve arrFields(intFieldCount)
' Makes sure the "field" has a non-zero length.
If (intCursor - intStart > 0) Then
' Extract the field value.
strValue = Mid(strLine, intStart, intCursor -
intStart)
' If it's a quoted string, use Mid to
' remove outer quotes and replace inner
' doubled quotes with single.
If (Left(strValue, 1) = QUOTE) Then
arrFields(intFieldCount) = Replace(Mid(strValue,
2, Len(strValue) - 2), QUOTE2, QUOTE)
Else
arrFields(intFieldCount) = strValue
End If
Else
' An empty field is an empty array element.
arrFields(intFieldCount) = Empty
End If
' increment for next field.
intFieldCount = intFieldCount + 1
intStart = intCursor + 1
End If
End Select
Next
' Return the array.
CSVParse = arrFields
End Function
--
Richard
Microsoft MVP Scripting and ADSI
Hilltop Lab -
http://www.rlmueller.net