Home » excel » excel – Loop and replace two or more spaces with only one

excel – Loop and replace two or more spaces with only one

Posted by: admin May 14, 2020 Leave a comment


I want to replace all multiple spaces in cells in my range A1:K1000. So if 2 or more spaces, then replace them with one space " ".

My current code replaces spaces that are " " (2) spaces. How to adjust it to work with 2 or more spaces? So it will handle cases like " ", " ", " " etc.

Here is my code:

Sub RemoveSpaces()

Dim r1 As Range
Set r1 = ActiveSheet.Range("A1:K1000") 
r1.Replace _
      What:=Space(2), _
      Replacement:=" ", _
      SearchOrder:=xlByColumns, _
Set r1 = r1.Find(What:=Space(2))
If Not r1 Is Nothing Then
   Call RemoveSpaces
End If
End Sub
How to&Answers:

There is no need to loop cells:

enter image description here

Sub Test()

Dim rng As Range
Set rng = Sheets("Sheet1").Range("A1:A3")
rng.Value = Application.Trim(rng)

End Sub

enter image description here


So from Scott Craner comment, solution to this question seems to be:

Sub RemoveSpaces()

    Dim A As Range

    Set A = ActiveSheet.Range("A1:K1000") 

    For Each cell In A
    cell.Value = WorksheetFunction.Trim(cell)

End Sub