Please Note: This article is written for users of the following Microsoft Excel versions: 2007, 2010, and 2013. 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

by Allen Wyatt
(last updated October 27, 2016)

3

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.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (12593) applies to Microsoft Excel 2007, 2010, and 2013. 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

Working on Shared Templates

In many companies it is common to have standard templates accessible through the internal network. If you have templates ...

Discover More

Sharing Headings with Others

Headings form the outline of your document and hopefully give it an easy-to-follow organization. If you want to share those ...

Discover More

Setting the Wrapping Default for Objects

Want to have objects such as text boxes and shapes always appear using some formatting you like? Here are some ideas on ...

Discover More

Save Time and Supercharge Excel! Automate virtually any routine task and save yourself hours, days, maybe even weeks. Then, learn how to make Excel do things you thought were simply impossible! Mastering advanced Excel macros has never been easier. Check out Excel 2010 VBA and Macros today!

MORE EXCELTIPS (RIBBON)

Worksheet Events

You can create macros that are automatically executed whenever certain events occur within a worksheet. This tip details what ...

Discover More

Forcing Manual Calculation For a Workbook

If you have a large, complex workbook, you may want to make sure that it is always calculated manually instead of ...

Discover More

Sheets for Months

One common type of workbook used in offices is one that contains a single worksheet for each month of the year. If you need ...

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 for this tip:

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}] in your comment text. You’ll be prompted to upload your image when you submit the comment. 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 two more than 9?

2016-10-27 08:42:39

Kevin Moynihan

This is a quick cleaner I use when I've imported data from another application. This removes all the extra spaces and hidden/non-printable Characters.
Sub Data_Cleaner()
'
' Macro to clean and trim data elements in a spreadsheet
' works on any size spreadsheet
'
Dim r As Long 'Declare a variable for counting rows
Dim C As Long 'Storage variable for counting columns
Dim SheetName ' Storage variable for open sheet name
Dim Columnl As Long
Dim Rowl As Long
Dim Bad As Variant ' unseen character that messes up other files when exporting

If (vbYes <> (MsgBox("Are you sure you want to Clean and Trim all cells in the worksheet?", _
vbYesNo, "Data Cleaner"))) Then
Exit Sub
End If
Application.Calculation = xlManual ' this stops calculations in sheets from running
Application.ScreenUpdating = False
SheetName = ActiveSheet.Name 'stores the name of the open worksheet
Bad = Chr(160)
Rowl = ActiveSheet.Cells.Find(What:="*", SearchDirection:=xlPrevious, SearchOrder:=xlByRows).Row
'finds last row with a real character in it
Columnl = ActiveSheet.Cells.Find(What:="*", _
SearchDirection:=xlPrevious, _
SearchOrder:=xlByColumns).Column
'finds last column with a real character in it
For r = 1 To Rowl
For C = 1 To Columnl
Cells(r, C).Value = Application.WorksheetFunction.Substitute(Cells(r, C).Value, Bad, "")
Cells(r, C).Value = Application.WorksheetFunction.Clean(Cells(r, C).Value)
Cells(r, C).Value = Application.WorksheetFunction.Trim(Cells(r, C).Value)
On Error Resume Next
If Len(Cells(r, C).Value) = 0 Then
Cells(r, C).ClearFormats
On Error Resume Next
End If
Next C
Next r
Application.Calculation = xlAutomatic ' this sets calculations back to automatic
Application.ScreenUpdating = True
MsgBox "Finished!", vbOKOnly, "Data Cleaner"
End Sub


2016-10-27 08:38:24

Dave Unger

As it looks like the extra spaces got removed in my previous comment, I'm now substituting a "-" for a space, just to get by the auto-formatting.
So, if you also need to remove extra spaces from inside the text, use the worksheet function "Trim". E.g., Application.Trim("----Big---text---") will return "Big-text". Remember, change the "-" to a space.


2016-10-27 08:21:24

Dave Unger

In addition, if you also need to remove extra spaces from inside the text, use the worksheet function "Trim". E.g., Application.Trim(" Big text ") will return "Big text".


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.

Links and Sharing