Search code examples
excelwhitespacetrimremoving-whitespacevba

How can I remove all trailing whitespace from my excel column?


I used the trim function to remove the trailing spaces in column list of names in excel. However, there are still quite a few names that have additional whitespace after the name that is not removed.

I also tried to create my own:

Sub NoSpaces()
    Dim c As Range
    For Each c In Selection.Cells
        c.Value = Replace(c.Value, Chr(160), Chr(32))
    Next
End Sub

However, I get the error:

Compile Error:

Sub or Function not defined

Any help would be appreciated.

Edit: Reflected method change to "Replace" as suggested.


Solution

  • It was two parts together:

    First convert the non-breaking spaces:

    Sub ConvertNonBreakingSpaces()
    Dim c As Range
        For Each c In Selection.Cells
            c.Value = Replace(c.Value, Chr(160), Chr(32))
        Next
    End Sub
    

    Then remove all the normal spaces (chr(32)) using the Trim function.

    Sub ClearSpaces()
    Dim c As Range
        For Each c In Selection.Cells
            c.Value = Trim(c.Value)
        Next
    End Sub