This routine can be used to parse a passed string and fill the passed dynamic array with the values.
Parameters
sTextIn - The string to parse.
sDelim - The delimiter (may be of variable length)
aValues() - A dynamic array (un-dimensioned). When the function returns, this array will contain the parsed string fragments. Since the array is passed by reference (the Visual Basic default), it can be used by the calling procedure. If the array was passed ByVal, the calling procedure would not be able to use the values filled into the array and this routine would be worthless.
Return Value
Number of elements in the array.
Routine
Function iParseAndFillArray (sTextIn As String, _
sDelim As String, aValues() As String) As Integer
Dim iArrCt As Integer
Dim iCurPos As Integer
Dim iLenAssigned As Integer
Dim iCurStrLen As Integer
'Initilize counts
iArrCt = 1
iCurPos = 1
iLenAssigned = 1
'Get lenght of text to parse
iCurStrLen = Len(sTextIn)
Do
'Re-allocate array keeping previous elements
ReDim Preserve aValues(1 To iArrCt) As String
'Get the current segment (not including delimiter)
iCurStrLen = (InStr(iCurPos, sTextIn, sDelim) _
- iCurPos)
If iCurStrLen < 0 Then
'If delimiter not found, we have the last
'segment. Assign the value to array (the
'last, righthand part)
aValues(iArrCt) = Right$(sTextIn, _
(Len(sTextIn) - (iLenAssigned - 1)))
'Done!
Exit Do
Else
'Assign the value to array
aValues(iArrCt) = _
Mid$(sTextIn, iCurPos, iCurStrLen)
End If
'Assign start position of next element
'Add length of current string to length assigned
'var.
iLenAssigned = iLenAssigned + _
(Len(aValues(iArrCt)) + Len(sDelim))
'Set the new starting position (ahead of current
'delimiter) for next extraction
iCurPos = iLenAssigned
'Increment array index for next element
iArrCt = iArrCt + 1
Loop
'Return # elements in array
iParseAndFillArray = UBound(aValues)
End Function
Example
Dim sArray() As String
Dim R As Integer
R = iParseAndFillArray("VB|TIPS|&|TRICKS", "|", sArray())
|