Please Note: This article is written for users of the following Microsoft Word versions: 2007, 2010, 2013, 2016, 2019, and Word in Microsoft 365. If you are using an earlier version (Word 2003 or earlier), this tip may not work for you. For a version of this tip written specifically for earlier versions of Word, click here: Trimming Spaces from Strings.
Written by Allen Wyatt (last updated August 29, 2020)
This tip applies to Word 2007, 2010, 2013, 2016, 2019, and Word in Microsoft 365
It is often necessary to trim spaces off of strings when programming in VBA. 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 would 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.
WordTips is your source for cost-effective Microsoft Word training. (Microsoft Word is the most popular word processing software in the world.) This tip (13113) applies to Microsoft Word 2007, 2010, 2013, 2016, 2019, and Word in Microsoft 365. You can find a version of this tip for the older menu interface of Word here: Trimming Spaces from Strings.
Learning Made Easy! Quickly teach yourself how to format, publish, and share your content using Word 2013. With Step by Step, you set the pace, building and practicing the skills you need, just when you need them! Check out Microsoft Word 2013 Step by Step today!
Need to use a macro to create a text string? One easy way to do it is to use the String function, described in this tip.Discover More
If your macro needs to determine the status of the Caps Lock key, you need the code in this tip. Just use the Information ...Discover More
Want to grab some interactive input from a user in your macro? The best way to do that is with the InputBox function, ...Discover More
FREE SERVICE: Get tips like this every week in WordTips, a free productivity newsletter. Enter your address and click "Subscribe."
Got a version of Word that uses the ribbon interface (Word 2007 or later)? This site is for you! If you use an earlier version of Word, visit our WordTips site focusing on the menu interface.
Visit the WordTips channel on YouTube