Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing All Spaces in String

Tags:

excel

vba

I created a macro for removing all whitespace in a string, specifically an email address. However it only removes about 95% of the whitespace, and leaves a few.

My code:

Sub NoSpaces()
    Dim w As Range

    For Each w In Selection.Cells
        w = Replace(w, " ", "")
    Next
End Sub

Things I have tried to solve the issue include:

~ Confirmed the spaces are indeed spaces with the Code function, it is character 32 (space)
~ Used a substitute macro in conjuction with the replace macro
~ Have additional macro utilizing Trim function to remove leading and trailing whitespace
~ Made a separate macro to test for non-breaking spaces (character 160)
~ Used the Find and Replace feature to search and replace spaces with nothing. Confirmed working.

I only have one cell selected when I run the macro. It selects and goes through all the cells because of the Selection.Cells part of the code.

A few examples:

1 STAR MOVING @ ATT.NET
322 [email protected]
ALEZZZZ@AOL. COM. 

These just contain regular whitespace, but are skipped over.

like image 385
PatrykChristopher Avatar asked Feb 17 '17 19:02

PatrykChristopher


People also ask

How do I remove all spaces from a string?

To remove all white spaces from String, use the replaceAll() method of String class with two arguments, i.e. Program: Java.

How do you remove all spaces from a string in Python?

Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.

How do I remove all spaces from a string in Java?

Java has inbuilt methods to remove the whitespaces from the string, whether leading, trailing, both, or all. trim() method removes the leading and trailing spaces present in the string. strip() method removes the leading and trailing spaces present in the string.


2 Answers

Try this:

Sub NoSpaces()
Selection.Replace " ", ""
End Sub
like image 97
user1274820 Avatar answered Oct 27 '22 05:10

user1274820


Just use a regular expression:

'Add a reference to Microsoft VBScript Regular Expressions 5.5
Public Function RemoveWhiteSpace(target As String) As String
    With New RegExp
        .Pattern = "\s"
        .MultiLine = True
        .Global = True
        RemoveWhiteSpace = .Replace(target, vbNullString)
    End With
End Function

Call it like this:

Sub NoSpaces()
    Dim w As Range

    For Each w In Selection.Cells
        w.Value = RemoveWhiteSpace(w.Value)
    Next
End Sub
like image 31
Comintern Avatar answered Oct 27 '22 05:10

Comintern