The VBA Trim function removes the leading and trailing spaces from a supplied text string.
The syntax of the function is:
Where the String argument is the text string that you want to remove the leading and trailing spaces from.
The following example shows how the VBA Trim function can be used to remove one or more leading and/or trailing spaces from three different text strings.
' Remove the leading and trailing spaces from three text strings.
Dim name As String
Dim address As String
Dim postcode As String
name = "John Smith " ' has a trailing space
address = " 21 Smithson Street" ' has a leading space
postcode = " AB1 1CD " ' has several leading and trailing spaces
name = Trim( name )' After running the above code, the variable name = "John Smith",
address = Trim( address )
postcode = Trim( postcode )
' address = "21 Smithson Street" and postcode = "AB1 1CD"
As required, the Trim function in the above VBA code has removed all leading and trailing spaces from the supplied text strings.