Extracting the n-th Element From a StringExcel has many worksheet functions, but sometimes you'll find that it just doesn't have the function you need. In such a situation, it's time to roll your own. This tip describes a custom worksheet function (which can also be called from a VBA procedure) that extracts an element from a text string. For example, if a cell contains the text below, you can use the ExtractElement function to extract any of the substrings between the hyphens. 123-456-789-0133-8844 The formula below, for example, returns "0133", which is the fourth element in the string. The string uses a hyphen (-) as the separator. =ExtractElement("123-456-789-0133-8844",4,"-")
ExtractElement SyntaxThe ExtractElement function uses three arguments:
Usage Notes
The ExtractElement FunctionThe VBA code for the ExtractElement function is listed below. To use this function, copy the text and paste it into a VBA module. Function ExtractElement(Txt, n, Separator) As String
' Returns the nth element of a text string, where the elements
' are separated by a specified separator character
Dim Txt1 As String, TempElement As String
Dim ElementCount As Integer, i As Integer
Txt1 = Txt
' If space separator, remove excess spaces
If Separator = Chr(32) Then Txt1 = Application.Trim(Txt1)
' Add a separator to the end of the string (if necessary)
If Right(Txt1, 1) <> Separator Then Txt1 = Txt1 & Separator
' Initialize
ElementCount = 0
TempElement = ""
' Extract each element
For i = 1 To Len(Txt1)
If Mid(Txt1, i, 1) = Separator Then
ElementCount = ElementCount + 1
If ElementCount = n Then
' Found it, so exit
ExtractElement = TempElement
Exit Function
Else
TempElement = ""
End If
Else
TempElement = TempElement & Mid(Txt1, i, 1)
End If
Next i
ExtractElement=""
End Function
|