VBA macros · Data
VBA macro to trim spaces in selected cells in Excel
Remove leading, trailing and double spaces (including non-breaking spaces from web pages) from the text in the selected cells, leaving formulas alone.
Extra spaces are invisible and cause real trouble: lookups return #N/A, duplicates are not recognised and sorting goes wrong because Smith and *Smith * are different values. The TRIM function fixes that in a helper column, but then you have to copy the results back. This macro cleans the selected cells in place.
Option Explicit
Sub TrimSpacesInSelection()
Dim rng As Range, c As Range
Dim s As String
Dim n As Long
If TypeName(Selection) <> "Range" Then Exit Sub
' Only text constants: formulas and numbers are left alone
If Selection.Cells.CountLarge = 1 Then
If Not Selection.HasFormula And VarType(Selection.Value) = vbString Then Set rng = Selection
Else
On Error Resume Next
Set rng = Selection.SpecialCells(xlCellTypeConstants, xlTextValues)
On Error GoTo 0
End If
If rng Is Nothing Then
MsgBox "No text found in the selection.", vbInformation
Exit Sub
End If
Application.ScreenUpdating = False
For Each c In rng.Cells
s = Replace(c.Value, ChrW(160), " ") ' non-breaking spaces
s = Application.WorksheetFunction.Trim(s) ' ends + double spaces
If s <> c.Value Then
c.Value = s
n = n + 1
End If
Next c
Application.ScreenUpdating = True
MsgBox n & " cell(s) cleaned.", vbInformation
End SubHow to use it
- Open the workbook and press
Alt+F11(Mac:Opt+F11orFn+Opt+F11) to open the VBA editor. See The Developer tab and the VBA editor if you have never used it. - Choose Insert › Module. An empty code window opens on the right.
- Paste the whole code into that window. If the module already starts with
Option Explicit, do not paste that line twice. - Go back to Excel, press
Alt+F8(Mac:Opt+F8, or Tools › Macro › Macros), pickTrimSpacesInSelectionand click Run. - Select the cells, columns or whole sheet you want to clean before you run it.
- Save the file as an Excel Macro-Enabled Workbook (.xlsm). A normal .xlsx file throws the code away when you save it.
To have this macro ready in every workbook, keep it in your Personal Macro Workbook (PERSONAL.XLSB). If you do not have one yet, record any tiny macro with Store macro in: Personal Macro Workbook (see The macro recorder: record, read and clean up code), then paste this code into a module under VBAProject (PERSONAL.XLSB). The macro works on whichever workbook is active when you run it.
How it works
SpecialCells(xlCellTypeConstants, xlTextValues) picks only the cells that contain typed text, so formulas, numbers and empty cells are never touched. It raises an error when there are no such cells, hence the On Error Resume Next around it. There is one trap: called on a single cell, SpecialCells searches the whole sheet instead. The macro therefore handles a one-cell selection separately.
Text copied from web pages often contains the non-breaking space, character 160, which looks like a space but is not removed by any trim function. Replace(c.Value, ChrW(160), " ") turns it into a normal space first. Then WorksheetFunction.Trim does the cleaning. It is used instead of VBA's own Trim because the Excel version also squeezes double spaces inside the text to one, while VBA's Trim only removes spaces at the ends (see Working with text (strings) in VBA and Using Excel worksheet functions in VBA).
A cell is written back only if the text actually changed. That keeps the count honest and avoids needless writes.
Change it
To remove all spaces, for example from phone numbers or codes, replace the Trim line with s = Replace(s, " ", ""). To also strip line breaks (Alt+Enter inside a cell), add s = Replace(s, vbLf, " ") before trimming. To remove other non-printing characters, use s = Application.WorksheetFunction.Clean(s), the VBA version of CLEAN.
To clean only one column of a table, select that column before running; the macro limits itself to text cells anyway, so selecting the whole column is quick. If you also need to change capitals, run VBA macro to change text case (UPPER, lower, Proper) in Excel afterwards.
What can go wrong
00123 becomes the number 123 in a General-formatted cell, losing the leading zeros, and text such as 2026-03-01 becomes a date. If that matters, format the column as Text (Ctrl+1 › Number › Text) before running the macro.A macro cannot be undone with Ctrl+Z (Mac: Cmd+Z). Save the workbook, or make a copy with VBA macro to save a backup copy with a timestamp in Excel, before you run it on real data.
ChrW(160) is used rather than Chr(160) so the character is the same on every system and language setting.Related: VBA macro to change text case (UPPER, lower, Proper) in Excel, VBA macro to remove duplicates based on one column in Excel, TRIM.