The Computer Oracle

I need to find the last Space in a XLS Cell

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Future Grid Looping

--

Chapters
00:00 I Need To Find The Last Space In A Xls Cell
00:27 Accepted Answer Score 43
01:14 Answer 2 Score 11
02:09 Thank you

--

Full question
https://superuser.com/questions/680769/i...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#microsoftexcel #worksheetfunction

#avk47



ACCEPTED ANSWER

Score 43


If by blank value you mean "space", and by XLS you mean Excel, then you can use this formula (assuming the test you want to find the last space in is in A1):

=FIND("☃",SUBSTITUTE(A1," ","☃",LEN(A1)-LEN(SUBSTITUTE(A1," ",""))))

You can divide it into 3 parts:

  • LEN(A1)-LEN(SUBSTITUTE(A1," ","")) gives you the number of spaces, let's call it x,
  • SUBSTITUTE(A1," ","☃",[x]) will replace the xth space (so the last one) by a snowman,
  • FIND("☃",[...]) will give you the position of the snowman. Which is the position of the last space.



ANSWER 2

Score 11


Here's another way, any characters are allowed in A1 (even snowmen!)

=LOOKUP(2^15,FIND(" ",A1,ROW(INDIRECT("1:"&LEN(A1)))))

FIND has a third argument that defines the start position of the search, if you apply an array of integer values 1 to n (where n is the length of A1) to that parameter you get an array back with the last number being the position of the last space.

LOOKUP then extracts that number by searching for a value greater than any value that might be found in that array, in which case the last number is found

In Excel 2010 or later you could also use AGGREGATE function like this

=AGGREGATE(14,6,FIND(" ",A1,ROW(INDIRECT("1:"&LEN(A1)))),1)

FIND returns the same array as before and by using 14 as 1st argument of AGGREGATE and 1 as the last you get the largest value in the array, whilst ignoring errors [6]