How to remove spaces in between text?

The VBA Trim function is different than Excel's. Use Excel's Application.WorksheetFunction.Trim function instead.

Excel Trim will remove all spaces except a single space between words. VBA Trim will remove leading and trailing spaces.

Thank MS for using the same keyword for different functions.


Trim removes extra spaces at start and end, not in the middle of a string.

Function CleanSpace(ByVal strIn As String) As String
    strIn = Trim(strIn)

  ' // Replace all double space pairings with single spaces
    Do While InStr(strIn, "  ")
        strIn = Replace(strIn, "  ", " ")
    Loop

    CleanSpace = strIn
End Function

From here.

PS. It's not the most efficient way to remove spaces. I wouldn't use on many, very long strings or in a tight loop. It might be suitable for your situation.


I know this question is old but I just found it and thought I'd add what I use to remove multiple spaces in VBA....

cleanString = Replace(Replace(Replace(Trim(cleanString), _ 
 " ", " |"), "| ", ""), " |", " ") 'reduce multiple spaces chr(32) to one

Tags:

Excel

Vba