View Full Version : Extracting a specified block of characters from a delimited string


raskew
04-12-2009, 01:10 AM
In the process of responding to a post in another forum, I came across this function, which I hadn't used in years.
It allows the user to specify a delimiter and designated block (e.g. 1,2,3) and returns that block.
I don't know if I wrote it (would like to think so) or copied it from an unknown source. A search failed to turn up the function name. If it's yours, please let us know.

Public Function PassbackAnyword(pstrText As String, pintword As Integer, pstrdivider As String) As Variant
'Purpose: Given a string, a word and the divider,
' returns the specific word.
'Input: ? PassbackAnyword("1234*7890*8888", 2, "*")
'Output: 7890

Dim intLoop As Integer
Dim intPos As Integer
Dim intprev As Integer
Dim varstring As Variant

'Don't waste your time if the divider isn't in the string
If InStr(pstrText, pstrdivider) <> 0 Then

intPos = 1
intprev = 1

pstrText = pstrText & pstrdivider
For intLoop = 1 To pintword

intPos = InStr(intprev + 1, pstrText, pstrdivider)

If intPos <> 0 Then
If intLoop < pintword Then
intprev = intPos
End If
Else
intPos = intprev

End If

Next

varstring = Mid(pstrText, intprev, intPos - intprev)

If pintword > 1 And varstring <> "" Then
varstring = Right(varstring, Len(varstring) - 1)
End If
Else
'If it's the first word we want then it's all the string otherwise is nothing
If pintword = 1 Then
varstring = pstrText
End If
End If
If varstring = "" Or varstring = pstrdivider Then
varstring = Null
End If

PassbackAnyword = varstring
End Function

It eliminates a bunch of gyrations trying to get just that specific block of characters.

HTH - Bob

Guus2005
05-08-2009, 12:11 AM
It has the same functionality as my GetPart function.
http://www.access-programmers.co.uk/forums/showthread.php?t=130858
Obviously, in future Access versions this functionality should be added.