Return to VBA Code Examples

VBA Trim, LTrim, and RTrim Functions – Remove Spaces From Text

This tutorial will demonstrate how to use the Trim, LTrim, and RTrim VBA functions as well as the Trim worksheet function.

Trim Function

The VBA Trim function removes (“trims”) erroneous spaces before and after strings of text.

Trim Spaces Before and After Text

The VBA Trim function will remove spaces before and after strings of text:

Trim Multiple Spaces Before and After Text

This includes trimming multiple spaces before and after text:

VBA Trim will NOT Remove Multiple Spaces Between Words

However, the Trim function will not remove multiple spaces in between words:

Trim as a Worksheet Function

However, the Excel Trim worksheet function can be used to remove extra spaces between words:

trim worksheet remove extra spaces

 

 

 

 

 

Use Worksheet Trim Function in VBA

To use the Excel Trim Function in VBA, call it by using WorksheetFunction:

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro - A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users! automacro

Learn More!!

Difference Between WorksheetFunction.Trim and VBA Trim

This will demonstrate the differences between Trim and WorksheetFunction.Trim:

Use VBA to add Trim Function in a Range

The Trim Worksheet function can be added in a Range using property .Formula:

LTrim Function

The LTrim function removes spaces only from the left side of the word:

VBA Programming | Code Generator does work for you!

RTrim Function

The RTrim function removes spaces only from the right side of the word:

Trim, Ltrim and Rtrim do not remove spaces between words.

Remove all spaces from text

Trim will only remove extra spaces in between words, but to remove all spaces in a string of text, you can use the Replace Function: