Excel VBA Trim Function: Clean Up Text Fast
In this article
The VBA Trim function removes leading and trailing spaces from a text string, leaving single spaces between words intact. The shortest working form is Trim(" hello "), which returns "hello". It is the fastest way to clean data imported from CSV files, pasted from websites, or typed by different people, because stray spaces break lookups, comparisons, and numeric conversions without any visible sign. Nothing needs to be installed: Trim is a built-in VBA function available in every version of Excel that supports macros.
What You'll Need
- A Macro-Enabled Workbook (.xlsm) or an existing workbook where you have saved the VBA code separately.
- The Developer tab enabled on the ribbon. If you do not see it, go to File > Options > Customize Ribbon and tick Developer in the right-hand list. Labels can vary slightly by Excel version and region.
- Macros enabled for the workbook, or the file added to a trusted location.
- Sample cells containing text with extra spaces so you can see the effect immediately.
Step-by-Step
- Open the VBA editor. Press Alt+F11 (on a Mac, use the Developer tab > Visual Basic). The Microsoft Visual Basic for Applications window opens.
- Insert a module. In the editor menu, choose Insert > Module. A blank code pane appears on the right. Macros written in a module are callable from anywhere in the workbook, which is what you want for a reusable trim routine.
- Start a new procedure. Type the following skeleton, pressing Enter after each line:
Sub TrimSpaces()
Dim ws As Worksheet
Set ws = ActiveSheet
End Sub
The Dim line declares a worksheet object; Set points it at whichever sheet is active. If your macro works across several columns, this structure keeps the code readable.
- Point at the range you want to clean. Add a line such as
Dim r As RangeandFor Each r In ws.Range("A2:A100"). ChangeA2:A100to the actual range holding your text. Usews.UsedRangeif you do not know the size, but be aware thatUsedRangecan include blank or formatted cells. - Apply Trim and write the result back. Inside the loop, write
r.Value = Trim(r.Value). This reads the cell's text, strips the outer spaces, and assigns the cleaned string back to the same cell. Because the code overwrites the cell, keep a backup of the original column if the data is hard to reproduce. - Close the loop and finish. Add
Next rand confirm theEnd Subline is present. The complete sub then looks roughly like this:
Sub TrimSpaces()
Dim ws As Worksheet
Dim r As Range
Set ws = ActiveSheet
For Each r In ws.Range("A2:A100")
r.Value = Trim(r.Value)
Next r
End Sub
- Run it. Press F5 with the cursor inside the sub, or go back to Excel and press Alt+F8, select TrimSpaces, and click Run. Check the sheet: leading and trailing spaces are gone.
- Understand what Trim does not remove. VBA's
Trimonly deletes the standard space character (character code 32). It does not remove tabs, line breaks, or non-breaking spaces. To remove non-breaking spaces, add a line usingReplace:r.Value = Replace(r.Value, Chr(160), " ")before the Trim line. Character code 160 is the non-breaking space that often arrives with web and HTML data. - Remove line breaks and tabs the same way. Use
Replace(r.Value, Chr(10), " ")for line feeds andReplace(r.Value, Chr(9), " ")for tabs. Chain them so all three clean-up passes happen before the final Trim. - Handle errors and non-text cells. Numbers, dates, and error values behave differently. Wrapping the value check prevents problems: use
If Not IsError(r.Value) Thenbefore assigning. For a text-only subset, test withIf VarType(r.Value) = vbString Then. This stops the macro from attempting string operations on cells that contain #N/A or dates. - Save and test against a copy. Press Ctrl+S, keeping the .xlsm format. Run the macro on a duplicated sheet first so you can compare results. Compare with a formula such as
=LEN(TRIM(A2))in a helper column to prove there is no residual whitespace. - Convert the sample to a reusable function if needed. If you want to trim without overwriting, declare
Function CleanText(s As String) As String, returnTrim(s)inside the body, and call it from a formula in an adjacent column. This keeps the source data intact and is the safer route on a shared workbook.
Common Mistakes
Treating Trim as complete cleanup. Many people assume Trim removes all invisible characters. It does not. Non-breaking spaces and line breaks survive, so comparisons with clean data still fail until you add Replace calls for Chr(160), Chr(9), and Chr(10).
Confusing the worksheet TRIM with the VBA Trim. Excel's worksheet function TRIM removes all extra spaces including repeated spaces between words. VBA's Trim preserves single interior spaces but does not collapse double spaces. Covering r.Value = Application.WorksheetFunction.Trim(r.Value) gives worksheet-style behaviour inside a macro.
Running on the wrong sheet. Using ActiveSheet means the macro cleans whichever sheet is visible when you press Run. Name the sheet explicitly, for example Set ws = ThisWorkbook.Worksheets("Data"), to prevent silent damage on a different tab.
Forgetting to enable macros. In a security-restricted workbook the macro will not run and no error appears. Check the yellow security bar and Trust Center settings before assuming the code is broken.
Writing to merged cells. Assigning values into merged ranges throws an error or clears the merge. Unmerge first or skip those cells.
Tips
Trim early in your import process. Cleaning a column right after pasting beats hunting for bad lookups later. Combine Trim with LCase or UCase so text is normalised for both spacing and case in one pass. Cache the worksheet range rather than reading Cells repeatedly inside the loop; for very large ranges, store values in a variant array, trim in memory, then write the array back, which is dramatically faster. Use Replace before Trim in the chain, so newly created edge spaces from the replacements are also removed. Keep a commented copy of the macro in a personal workbook so other files can use it. Test on a copy of the data. Add a simple MsgBox at the end that counts how many cells changed so you can confirm the macro actually touched data.
Troubleshooting
The macro runs but spaces remain. The characters are likely Chr(160) or tabs. Inspect a cell with =CODE(MID(A1,1,1)) to identify the leading character code, then add the matching Replace call.
Compile error: expected end of statement. Check for a missing closing parenthesis in the Trim( line or a missing Then on an If statement. Watch for curly quotation marks copied from a webpage, which VBA does not accept; retype straight quotes.
Run-time error 13, type mismatch. A cell in the loop holds an error value or object. Add the IsError guard covered above.
Output looks unchanged although it should not be. Confirm you are looking at the correct sheet and that the range string matches the data. A common slip is trimming A2:A100 when the text actually sits in column B.
Numbers stop working after trimming. A trimmed value can still be text, so SUM returns zero. Convert it with r.Value = Val(Trim(r.Value)) only for numeric columns, or use the Value2 property and confirm with =ISNUMBER().
If that did not work, step through the macro line by line with F8, watch each cell, and confirm the saved file is .xlsm rather than .xlsx, which strips VBA code entirely on save.
Frequently Asked Questions
Does VBA Trim remove multiple spaces between words?
No. It strips only the spaces at the start and end of the string. Use Application.WorksheetFunction.Trim if you also need interior double spaces collapsed.
Can Trim be used directly in a cell formula?
No. VBA's Trim is a macro function. In a worksheet cell, use the TRIM() formula instead. A user-defined function that wraps Trim is the only way to reuse the VBA version in a cell.
Why does Trim leave a space that will not go away?
The character is probably a non-breaking space, Chr(160), which Trim ignores by design. Replace it with a normal space first, then trim.
Does Trim work on numbers?
It converts them to text before trimming, so trailing zeros and formatting can change. Only apply it to columns you know hold text, or convert back with Val.
Is VBA Trim case sensitive?
No. Trimming only removes spaces, so case is left untouched. Pair it with LCase or UCase if you need normalised case too.
Will trimming affect cells with formulas?
Yes, if the code writes to them. The formula is replaced by a static value. Either skip formula cells with a check on HasFormula or trim the underlying source data instead.