Remove Spaces from Strings in VBA

In Martin Green's VBA tutorial there's a section for removing spaces from a string. But it involves this odd "Goto" loop which looks like spaghetti code.

Here's a simple way to remove spaces from any given input string.

Public Function RemoveSpaces(strInput As String) As String
  RemoveSpaces = Replace(strInput, " ", "")
End Function

Note that this function will blindly remove all spaces from the input string, which is different from removing excess spaces. Microsoft has an article with code demonstrating how to do just that.

Site last updated: May 17, 2012

Random Data Generator