Extract the last substring from a cell
The answer provided by @Jean provides a working but obscure solution (although it doesn't handle trailing spaces)
As an alternative consider a vba user defined function (UDF)
Function RightWord(r As Range) As Variant
Dim s As String
s = Trim(r.Value)
RightWord = Mid(s, InStrRev(s, " ") + 1)
End Function
Use in sheet as=RightWord(A2)
This works, even when there are middle names:
=MID(A2,FIND(CHAR(1),SUBSTITUTE(A2," ",CHAR(1),LEN(A2)-LEN(SUBSTITUTE(A2," ",""))))+1,LEN(A2))
If you want everything BUT the last name, check out this answer.
If there are trailing spaces in your names, then you may want to remove them by replacing all instances of A2
by TRIM(A2)
in the above formula.
Note that it is only by pure chance that your first formula =RIGHT(A2,FIND(" ",A2,1)-1)
kind of works for Alistair Stevens
. This is because "Alistair"
and " Stevens"
happen to contain the same number of characters (if you count the leading space in " Stevens"
).
Try this function in Excel:
Public Shared Function SPLITTEXT(Text As String, SplitAt As String, ReturnZeroBasedIndex As Integer) As String
Dim s() As String = Split(Text, SplitAt)
If ReturnZeroBasedIndex <= s.Count - 1 Then
Return s(ReturnZeroBasedIndex)
Else
Return ""
End If
End Function
You use it like this:
First Name (A1) | Last Name (A2)
Value in cell A1 = Michael Zomparelli
I want the last name in column A2.
=SPLITTEXT(A1, " ", 1)
The last param is the zero-based index you want to return. So if you split on the space char then index 0 = Michael and index 1 = Zomparelli
The above function is a .Net function, but can easily be converted to VBA.