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

Rounding Time

Need to round the time in a cell to a certain value? There are a couple of ways you can do this with a formula.

Discover More

Pop-up Windows in Word

Want to add a small pop-up window over a word in your document? There is no way to do this directly in Word, but you can use ...

Discover More

Non-standard Sorting

Information in a cell can be entered using line feeds, which results in multiple lines of data in the same cell. If you later ...

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)

Renaming Worksheets Based On a List

Renaming a worksheet within a macro is a relatively easy task. When you start renaming based on a range of names, though, the ...

Discover More

Specifying Location for a Message Box

When writing macros, you may want to position a message box at a specific location on the screen. This can't be done in ...

Discover More

Automating the Importing of Macros

Macros are great when it comes to automating how you work with your workbooks. What if you want to fundamentally change the ...

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}] in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 8Mpixels. 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 0 + 7?

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.