How to get last word in a cell using Excel Formula

喜欢而已 提交于 2020-01-30 11:34:15

问题


I am trying to get the last word in a cell however, it does not seem to be appearing getting the last word of the cell. It seems to get the partial match and not working correctly. I am using =IFERROR(RIGHT(AP2,SEARCH(" ",AP2)-1),AP2). This works great for getting the first word in a cell even where the first word is the only word in a cell. Any ideas on why this is not getting the last word correctly?


回答1:


You may try this UDF which can be used in another sub routine or on the worksheet as well.

Function GetLastWord(ByVal Str As String) As String
Dim arrStr
arrStr = Split(Str, " ")
GetLastWord = arrStr(UBound(arrStr))
End Function

If you need to use it on the worksheet, assuming your string is in A1 then try this...

=GetLastWord(A1)



回答2:


Your formula is based on the first occurrence of a space in the string.

For example with "Man City V Stoke" in the formula SEARCH(" ",AP11) is looking for the first occurrence of a space which occurs at position 4. You are then subtracting 1 from this and using this as the number of characters to return from the right of the original string. So you get Right("Man City V Stoke",3) which is "oke".

A better way is a formula such as

=TRIM(RIGHT(SUBSTITUTE(AP11," ",REPT(" ",LEN(AP11))),LEN(AP11))) find text after last space

The part written: =SUBSTITUTE(AP1," ",REPT(" ",LEN(AP1)))

This inserts spaces the length of the string (16) in place of every occurrence of a space i.e.

Man                City                V                Stoke

When you then do RIGHT(SUBSTITUTE(AP11," ",REPT(" ",LEN(AP11))),LEN(AP11)) you are guaranteed to only get whitespace followed by the last word. You then use TRIM to get rid of this white space.




回答3:


As far as I can tell the below worked for me.

=TRIM(RIGHT(SUBSTITUTE(AP40," ",REPT(" ",100)),100))

I can only assume my other method is unreliable at getting the last word.



来源:https://stackoverflow.com/questions/46522164/how-to-get-last-word-in-a-cell-using-excel-formula

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!