Tag Archives: String Manipulation

VBA – Extract the Nth Term from a String

The heading says it all. Below is another straightforward function to extract the Nth element/term from a input string. I have offset the Element number so it is not 0 based, but rather 1 based. This to make it intuitive to use.

'---------------------------------------------------------------------------------------
' Procedure : ExtractNthTerm
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Extract the nth term form a string
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sString   : Full string to extract the term from
' sDelim    : Separating delimiter character
' iTermNo   : No of the term to extract
'
' Usage:
' ~~~~~~
' ExtractNthTerm("William is a great guy.", " ", 4)  -> will return great
' ExtractNthTerm("apple,pear,orange,mango,lemon", ",", 3)  -> will retun orange
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2009-Feb-7                Initial Release
'---------------------------------------------------------------------------------------
Function ExtractNthTerm(sString As String, sDelim As String, iTermNo As Integer) As String
    On Error GoTo Error_Handler

    aTerms = Split(sString, sDelim)
    ExtractNthTerm = aTerms(iTermNo - 1)

Error_Handler_Exit:
    On Error Resume Next
    Exit Function

Error_Handler:
    If Err.Number = 9 Then
'        MsgBox "You have requested a Term No that exceed the supplied String no of term." & vbCrLf & vbCrLf & _
'               "You have requested term " & iTermNo & " and there only appears to be " & UBound(aTerms) + 1 & _
'               " in the supplied string (" & sString & ").", vbCritical + vbOKOnly
        ExtractNthTerm = ""
    Else
        MsgBox "The following error has occurred." & vbCrLf & vbCrLf & _
               "Error Number: " & Err.Number & vbCrLf & _
               "Error Source: " & sModName & "/ExtractNthTerm" & vbCrLf & _
               "Error Description: " & Err.Description, _
               vbCritical, "An Error has Occurred!"
    End If
    Resume Error_Handler_Exit
End Function