Saturday, 17 November 2007

Some CSV functions for VBA

feel free to use!
Function getCountCSV(ByVal list As String) As String
Dim number As Integer
number = 0
While Len(list) <> 0
Call getNextCSV(list)
number = number + 1
Wend
getCountCSV = number
End Function

Function getNextCSV(list As String) As String
Dim commaPosition As Integer
commaPosition = InStr(list, ",")
If (commaPosition = 0) Then commaPosition = InStr(list, ";")
If (commaPosition <> 0) Then
getNextCSV = Trim$(Mid$(list, 1, commaPosition - 1))
list = Trim$(Mid$(list, commaPosition + 1, Len(list) - commaPosition))
Else
getNextCSV = Trim$(list)
list = vbNullString
End If
End Function

Function getCSVValue(list As String, index As Integer) As String
' list is the text with comma separated values
' index is starting from 0
' returns the value at the given position in the list
Dim counter As Integer
Dim element As String
Dim listcsv As String
counter = 0
listcsv = list
element = getNextCSV(listcsv)
While (counter <> 0)
element = getNextCSV(listcsv)
counter = counter + 1
Wend
getCSVValue = element
End Function

No comments: