Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove ONLY leading and trailing spaces while leaving spaces in between words alone with an excel formula?

In excel, TRIM() will remove all spaces before and after text, while also removing any duplicate spaces in between words.

Is there a formula or combination thereof that will do the same as TRIM() but leave spaces between words as-is?

In the following example, I'm looking for a formula that will accomplish that of the fictitious formula "WXYZ":

TRIM(" Omicron Persei 8 ") = "Omicron Persei 8"
WXYZ(" Omicron Persei 8 ") = "Omicron Persei 8"

Note that I've read somewhere that TRIM() in VBA will work like that of WXYZ above. However, I'm looking for a formula solution.

like image 540
Bort Avatar asked Nov 17 '16 13:11

Bort


People also ask

What function will be used to remove only leading and trailing spaces?

The TRIM function is fully automatic. It removes removes both leading and trailing spaces from text, and also "normalizes" multiple spaces between words to one space character only.

How do I get rid of unnecessary spaces in Excel?

You can also remove spaces using the Find/Replace feature in Excel. Click CTRL+F to open the Find dialog box, then click the Replace tab. Enter one space ” ” in the Find what: field and leave the Replace with: field empty to remove all spaces.


1 Answers

I believe this should work (assuming your string is located at A1):

=MID(A1, FIND(LEFT(TRIM(A1),1),A1), (LEN(A1)-MATCH(RIGHT(TRIM(A1),1),INDEX(MID(A1,LEN(A1)-ROW(INDIRECT("1:"&LEN(A1)))+1,1),0),0)-FIND(LEFT(TRIM(A1),1),A1)+2)

FIND(LEFT(TRIM(A1),1),A1) returns the location of the first non-space character in the string

MATCH(RIGHT(TRIM(A1),1),INDEX(MID(A1,LEN(A1)-ROW(INDIRECT("1:"&LEN(A1)))+1,1),0),0) returns the location of the last non-space character in the string from right-to-left.

like image 163
aakash Avatar answered Jan 12 '23 23:01

aakash