Extracting a specified block of characters from a delimited string (1 Viewer)

Status
Not open for further replies.

raskew

AWF VIP
Local time
Today, 12:09
Joined
Jun 2, 2001
Messages
2,734
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.

Code:
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
 
Last edited:
Status
Not open for further replies.

Users who are viewing this thread

Top Bottom