Visual Basic Tips / Getting rid of spaces on the ends of strings.

Often you may want to get rid of extra spaces on the ends of string values for some reason or another. This is a very simple thing to accomplish due to VB having built in Trim() functions.

There are six trim functions built into Visual Basic. LTrim(), RTrim(), Trim(), LTrim$(), RTrim$(), and Trim$().

The first three return a data type of Variant. The three with the $ symbol in them are designed strictly for use with variables that are explicitly declared to be of string data types. If you're dealing with variables that have been declared as type String you'll want to use the functions with the $ to prevent data type mismatch errors.

To get rid of all extra spaces on both ends of a string pass it to the Trim() or Trim$() function

    StringVar = Trim(StringVar)

To get rid of the extra spaces at the front of a string only:

    StringVar = LTrim(StringVar)
or
    StringVar = LTrim$(StringVar)

To get rid of the extra spaces at the end of a string only:

    StringVar = RTrim(StringVar)
or
    StringVar = RTrim$(StringVar)