Please Note: This article is written for users of the following Microsoft Excel versions: 2007, 2010, 2013, 2016, 2019, Excel in Microsoft 365, and 2021. If you are using an earlier version (Excel 2003 or earlier), this tip may not work for you. For a version of this tip written specifically for earlier versions of Excel, click here: Trimming Spaces from Strings.

Trimming Spaces from Strings

Written by Allen Wyatt (last updated February 24, 2024)
This tip applies to Excel 2007, 2010, 2013, 2016, 2019, Excel in Microsoft 365, and 2021


8

It is often necessary to trim spaces off of strings when programming macros. For instance, let's say you used the InputBox function to get some user input. The function returns a string, but you find out that the user hit the space bar a few times before typing a response. Thus, you end up with a string such as " My String," complete with leading spaces.

Fortunately, VBA provides several different functions to remove spaces from a string. The following are the three functions you could use:

MyVar = LTrim(MyVar)
MyVar = RTrim(MyVar)
MyVar = Trim(MyVar)

The first example ends up trimming all the spaces from the left end of the string, the second removes them from the right end, and the third removes them from both ends. You can use the function that you feel best fits your programming needs.

You should be aware that the VBA Trim function produces different results from the TRIM worksheet function. The TRIM function removes not only leading and trailing spaces, but also any extra spaces within the string itself. If you want to use the TRIM function in your macro, you can do so in this way:

MyVar = Application.TRIM(MyVar)

Note:

If you would like to know how to use the macros described on this page (or on any other page on the ExcelTips sites), I've prepared a special page that includes helpful information. Click here to open that special page in a new browser tab.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (12593) applies to Microsoft Excel 2007, 2010, 2013, 2016, 2019, Excel in Microsoft 365, and 2021. You can find a version of this tip for the older menu interface of Excel here: Trimming Spaces from Strings.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Backing Up Your Custom Dictionaries

When you work with the spelling checker quite a bit, you eventually end up with a sizeable custom dictionary. You might ...

Discover More

Getting Audible Feedback

Want to get a little bit of sound with your data? Excel can provide audible feedback that you may find helpful. Here's how.

Discover More

Condensing Figure Caption References

Word can automatically add captions to your figures. You can then reference those captions from within your document. If ...

Discover More

Program Successfully in Excel! John Walkenbach's name is synonymous with excellence in deciphering complex technical topics. With this comprehensive guide, "Mr. Spreadsheet" shows how to maximize your Excel experience using professional spreadsheet application development tips from his own personal bookshelf. Check out Excel 2013 Power Programming with VBA today!

More ExcelTips (ribbon)

Dissecting a String

VBA is a versatile programming language. It is especially good at working with string data. Here are the different VBA ...

Discover More

Counting Empty Colored Cells

There are a variety of ways that you might want to count the cells in your worksheet. One way is to figure out how many ...

Discover More

Displaying the Print Dialog Box in a Macro

Want to print a document by using a macro? One way is to display the Print dialog box and allow the user to interact with ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] (all 7 characters, in the sequence shown) in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is nine less than 9?

2024-03-06 15:43:50

J. Woolley

My Excel Toolbox now includes the TextSpaceChars macro to convert all UNICODE space characters (see Figure 1 below) into standard ASCII space without disturbing the format of individual characters. This macro applies to text constants within the current Selection. Undo (Ctrl+Z) is supported.
See https://sites.google.com/view/MyExcelToolbox/

Figure 1. 


2024-03-03 11:04:51

J. Woolley

@sandeep kothari
If you use Alex Blakenburg's code:
    arr = Selection.Value
    arr = Application.Substitute(arr, ChrW(160), "")
    Selection.Value = arr
Make sure Selection does not include any formula cells because formulas will be replaced with constants (similar to Paste Values).


2024-03-03 09:04:08

sandeep kothari

Thanks a lot for the valuable guidance, Woolley & Alex. These have made my day.


2024-03-03 00:03:16

Alex Blakenburg

@sandeep kothari, in terms of VBA.
Working directly with a range:-
Selection.Replace what:=ChrW(160), replacement:=""
If you are putting the range into an array for further processing then:-
Dim arr As Variant

arr = Selection.Value
arr = Application.Substitute(arr, ChrW(160), "")
Selection.Value = arr


2024-03-02 12:51:43

J. Woolley

@sandeep kothari
If cell A1 contains non-breaking space characters, try this:
=TRIM(SUBSTITUTE(A1,UNICHAR(160),CHAR(32)))
Repeat SUBSTITUTE(...) for any additional non-standard space characters like UNICHAR(8199) or UNICHAR(HEX2DEC("2007")).
See https://unicode-explorer.com/articles/space-characters
If A1 is replaced by a range array like A1:A9, a dynamic array is returned by Excel 2021+.


2024-03-02 04:16:42

sandeep kothari

Nice codes, Allen, Woolley & Alex. What is the code to delete other spaces, like CHAR 32, 160, etc?


2024-03-01 10:37:32

J. Woolley

My Excel Toolbox includes the following functions useful in cell formulas:
    =TrimHead(Text, [NumChars])
    =TrimTail(Text, [NumChars])
TrimHead trims leading characters from Text and returns the result. If optional NumChars < 1 (default), all leading space characters are trimmed; otherwise, NumChars leading characters are trimmed.
TrimTail is analogous except it trims trailing characters.
Here are abbreviated versions:

Function TrimHead(Text As String, Optional NumChars As Integer) As String
    If NumChars < 1 Then
        TrimHead = LTrim(Text)
    Else
        TrimHead = Mid(Text, (NumChars + 1))
    End If
End Function

Function TrimTail(Text As String, Optional NumChars As Integer) As String
    If NumChars < 1 Then
        TrimTail = RTrim(Text)
    Else
        Dim n As Integer
        n = Len(Text) - NumChars
        If n > 0 Then TrimTail = Left(Text, n) 'else return null default
    End If
End Function

My Excel Toolbox also includes the TextTrim macro to remove ALL extra spaces (begin, middle, end; like TRIM) from text constants in Selection without disturbing the format of individual characters. Here is an abbreviated version:

Sub TextTrim()
    Dim rText As Range, rCell As Range
    Dim sText As String, sTrim As String, nTrim As Integer, n As Integer
    On Error Resume Next
        'Intersect is necessary in case Selection.Cells.Count = 1
        Set rText = Intersect(Selection, _
            Selection.SpecialCells(xlCellTypeConstants, xlTextValues))
    On Error GoTo 0
    If rText Is Nothing Then
        MsgBox "There are no text constants in Selection", vbCritical
        Exit Sub
    Else
        rText.Select
        rText.Cells(1).Show
    End If
    For Each rCell In rText
        sText = rCell.Value
        sTrim = Application.WorksheetFunction.Trim(sText)
        nTrim = 1
        For n = 1 To Len(sText)
            If Mid(sText, n, 1) = Mid(sTrim, nTrim, 1) Then
                nTrim = nTrim + 1
            Else
                rCell.Characters(nTrim, 1).Delete
            End If
        Next n
    Next rCell
End Sub

The unabbreviated version of TextTrim supports Undo (Ctrl+Z).
See https://sites.google.com/view/MyExcelToolbox


2024-02-24 05:45:09

Alex Blakenburg

One of the things I love about Application.Trim is that it can take a range or an array as the argument, so you don't need to loop through the Range or Array eg
ActiveSheet.UsedRange.Value = Application.Trim(ActiveSheet.UsedRange.Value)


This Site

Got a version of Excel that uses the ribbon interface (Excel 2007 or later)? This site is for you! If you use an earlier version of Excel, visit our ExcelTips site focusing on the menu interface.

Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.