Excel TRIM VBA Function: Remove Leading and Trailing Spaces

The Excel TRIM VBA function is important to use when you are working with data derived from locations where there could be leading and trailing spaces. This could prevent you from identifying the content of the variable successfully.

This function is simple to use, see the example below.

Dim FindtheText As String

Dim Lookingatstring As String

FindTheText = TRIM(Lookingatstring)

'For this example, pretend the LookingatString = " Testing " with 2 spaces at the end

'and 2 leading spaces

'FindTheText will now equal "Testing" without the 2 trailing spaces

If you had an IF statement that was looking for an exact match such as “Testing” and you did not use the TRIM method, the logic would not identify the string as “Testing” but as “ Testing ” and not perform the appropriate logic.