'=RField(A1, 2)
Function RField(cell, pos As Integer, Optional delimit As String = " ")
Dim a() As String
a() = Split(cell, delimit)
RField = a(UBound(a) - pos + 1)
End Function
Excel Workbook | |||||
---|---|---|---|---|---|
A | B | C | |||
1 | This is a test to find the second to last word in a very long string. | long | long | ||
2 | This is a test to find the second to last word in a long string. | long | long | ||
3 | This is a test to find the second to last word in a string. | a | a | ||
4 | This is a test to find the second to last | to | to | ||
5 | 01019000 - Los dems 10 A | 10 | 10 | ||
Sheet1 |
Option Explicit
Option Compare Text
Function Get_Word(text_string As String, nth_word) As String
'
' http://www.ozgrid.com/News/jul-2005.htm
'
Dim lWordCount As Long
With Application.WorksheetFunction
lWordCount = Len(text_string) - Len(.Substitute(text_string, " ", "")) + 1
If IsNumeric(nth_word) Then
nth_word = nth_word - 1
Get_Word = Mid(Mid(Mid(.Substitute(text_string, " ", "^", nth_word), 1, 256), _
.Find("^", .Substitute(text_string, " ", "^", nth_word)), 256), 2, _
.Find(" ", Mid(Mid(.Substitute(text_string, " ", "^", nth_word), 1, 256), _
.Find("^", .Substitute(text_string, " ", "^", nth_word)), 256)) - 2)
ElseIf nth_word = "First" Then
Get_Word = Left(text_string, .Find(" ", text_string) - 1)
ElseIf nth_word = "Last" Then
Get_Word = Mid(.Substitute(text_string, " ", "^", Len(text_string) - _
Len(.Substitute(text_string, " ", ""))), .Find("^", .Substitute(text_string, " ", "^", _
Len(text_string) - Len(.Substitute(text_string, " ", "")))) + 1, 256)
End If
End With
End Function