VBA Tip: Trim

The Trim function allows you to remove unnecessary spaces at the beginning and end of a string.

Use:

Trim(string)


Example

Removal of unnecessary spaces at the beginning and end of the text in cell A3:

function trim excel vba
Sub example()

    myVariable = Trim(Range("A3"))
    
    MsgBox myVariable 'Returns "Excel-Pratique.com"

End Sub

Example 2

Removal of unnecessary spaces at the beginning and end of the text in "myVariable":

Sub example()

    myVariable = "     Excel-Pratique.com          "

    MsgBox Trim(myVariable) 'Returns "Excel-Pratique.com"

End Sub