Excel VBA Trim Function

The Trim function in VBA removes the leading and trailing spaces from the specified string.

Syntax

Trim (String)

Parameter

String (required) – This parameter represents the string from which you want to remove the leading and trailing spaces.

Return

This function returns a string after removing the leading and trailing spaces from the given string

Example 1

Sub TrimFunction_Example1()
 'Remove the leading spaces from two strings.
 Dim name As String, address As String
 name = " Joe Jonas   "     ' has a leading space
 address = "Street 34 Manhattan, US   "     ' has several leading spaces
 name = Trim(name) 
 ' The function will return the varaible name = "Joe Jonas"
 Cells(1, 1).Value = "Name : " + name
 address = RTrim(address)
 ' address: "Street 34 Manhattan, US"
 Cells(1, 2).Value = "Address: " + address
 End Sub 

Output

Name: Joe Jonas Address: Street   34 Manhattan, US
VBA Trim Function

Example 2

Sub TrimFunction_Example2()
 'Remove the leading spaces from two strings.
 Dim name As String, address As String
 IB = InputBox("Enter your first name")
 Lst_IB = InputBox("Enter your last name")
 'will the id after removing the spcaes and convering the string into lower case
 MsgBox ("Your email is: " + Trim(LCase(IB)) + Trim(LCase(Lst_IB)) + "@gmail.com")
 End Sub 

Output

VBA Trim Function2
VBA Trim Function3
VBA Trim Function4