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.
by Allen Wyatt
(last updated October 27, 2016)
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.
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!
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
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
Macros are great when it comes to automating how you work with your workbooks. What if you want to fundamentally change the ...Discover More
FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."
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.