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

Toggling Print Preview

Need to easily switch back and forth between print preview and your document? Here's a quick shortcut key you can use to make ...

Discover More

Printing Workbook Properties

Want to create a printed record of the properties associated with a workbook? There is no easy way to do it in Excel. Here's ...

Discover More

Changing the Default Font

It makes sense that when Excel creates a blank workbook, it must figure out which font to use for that workbook. Fortunately, ...

Discover More

Comprehensive VBA Guide Visual Basic for Applications (VBA) is the language used for writing macros in all Office programs. This complete guide shows both professionals and novices how to master VBA in order to customize the entire Office suite for their needs. Check out Mastering VBA for Office 2010 today!

More ExcelTips (ribbon)

Quickly Dumping Array Contents

Variable arrays are used quite often in macros. If you use an array once in your macro and then need to reuse it for ...

Discover More

Editing Macros

Even if you do nothing but record macros, sooner or later you will have a need to edit what you record. Here's how to get to ...

Discover More

Deleting Every X Rows

Grab some info from a source other than Excel, and you may find the need to delete a certain pattern of rows from a ...

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 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 8 - 2?

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.