This post will guide you how to remove leading and trailing spaces in cells in Excel. How do I remove leading or trailing spaces in a range of cells with a formula in Excel. How to remove trailing spaces from cells with VBA Macro in Excel.
Remove Trailing Spaces from Cells with Formula
If you want to remote all leading and trailing spaces from test string in one or more cells, you can use a formula based on the TRIM function.
For example, you have a list of data in range B1:B4 contain text string values, and you want to strip all leading and trailing spaces in the given range of cells, how to achieve it. You can use the following formula.
Type this formula into a blank cell and then press Enter key, and drag the AutoFill Handle over other cells to apply this formula.
This formula will remove both leading and trailing spaces from text string in cells.
Remove Trailing Spaces from Cells with VBA Macro
You can also use an Excel VBA Macro to remote all trailing spaces from a given range of cells. Just do the following steps:
#1 select one range of cells that you want to remove trailing spaces
#2 open your excel workbook and then click on “Visual Basic” command under DEVELOPER Tab, or just press “ALT+F11” shortcut.
#3 then the “Visual Basic Editor” window will appear.
#4 click “Insert” ->”Module” to create a new module.
#5 paste the below VBA code into the code window. Then clicking “Save” button.
Sub RemovTrailSpaces() Dim cel As Range For Each cel In Selection.Cells cel = Trim(cel) Next End Sub
#6 back to the current worksheet, then run the above excel macro. Click Run button.
#7 Let’s see the result.
- Excel TRIM function
The Excel TRIM function removes all spaces from text string except for single spaces between words. You can use the TRIM function to remove extra spaces between words in a string.The syntax of the TRIM function is as below:= TRIM (text)….