Explanation
The TRIM function is fully automatic. It removes both leading and trailing spaces from text strings, and also “normalizes” multiple spaces between words to one space character only. All you need to do is supply a reference to a cell.
TRIM with CLEAN
If you also need to remove line breaks from cells, you can add the CLEAN function like so:
=TRIM(CLEAN(text))
The CLEAN function removes a range of non-printing characters, including line breaks, and returns “cleaned” text. The TRIM function then takes over to remove extra spaces and returns the final text.
Other problematic characters
Note that CLEAN cannot remove all non-printing characters, notably a non-breaking space, which can appear in Excel as CHAR(160). By adding the SUBSTITUTE function to the formula, you can remove specific characters. For example, to remove a non-breaking space, you can use:
=TRIM(CLEAN(SUBSTITUTE(B1,CHAR(160)," ")))
Explanation
First, you should know that Excel contains two functions, CLEAN and TRIM, that can automatically remove line breaks and extra spaces from text. For example to strip all line breaks from a cell, you could use:
=CLEAN(B5)
For a quick demo of CLEAN and TRIM, watch this video .
In this case, however, we are removing line breaks and replacing them with commas , so we are using the SUBSTITUTE function instead of CLEAN. SUBSTITUTE can locate matching text anywhere in a cell, and replace it with the text of your choice. SUBSTITUTE can accept up to four arguments, but we are using only the first three like this:
=SUBSTITUTE(B5,CHAR(10),", ")
The text comes from cell B5.
The “old text” is entered as CHAR(10). This will match a line break character in a cell.
The “new text” is entered as “, “. This translates to a comma plus one space. We need the quotes because this is a text value.
SUBSTITUTE then replaces all line breaks in the cell with commas and returns the final result as text in C5. Because “old text” is an argument, you can change the comma to any other text you like.