VBA Function: Trim

The VBA Trim function returns a string after removing leading and trailing spaces from the string.

Usage:

Trim(text)


Example of Usage

Using the Trim function to remove unnecessary spaces at the beginning and end of a string:

Sub example()

    MsgBox Trim("test") 'Returns: "test"
    MsgBox Trim("   test") 'Returns: "test"
    MsgBox Trim("test   ") 'Returns: "test"
    MsgBox Trim("   test   ") 'Returns: "test"
    MsgBox Trim("   test   test   ") 'Returns: "test   test"
    MsgBox Trim("      ") 'Returns: ""
    
End Sub

To remove only spaces from the left side of the string, use the LTrim function:

Sub example()

    MsgBox LTrim("   test") 'Returns: "test"
    MsgBox LTrim("test   ") 'Returns: "test   "
    MsgBox LTrim("   test   ") 'Returns: "test   "
    MsgBox LTrim("   test   test   ") 'Returns: "test   test   "
    
End Sub

To remove only spaces from the right side of the string, use the RTrim function:

Sub example()

    MsgBox RTrim("   test") 'Returns: "   test"
    MsgBox RTrim("test   ") 'Returns: "test"
    MsgBox RTrim("   test   ") 'Returns: "   test"
    MsgBox RTrim("   test   test   ") 'Returns: "   test   test"
    
End Sub