clean a Word document from multpile whitespace characters
<p>I am trying to clean each line of selected text in Word so that any not needed characters (tab, multiple spaces, multiple new line characters, empty lines) will be deleted.</p>

<p>Let's say I have a text:</p>

<pre><code>John        Smith 



John    Anderson Smith  

John           A. Smith     
J.A. Smith
</code></pre>

<p>I would like to achieve the following:</p>

<pre><code>John Smith 
John Anderson Smith 
John A. Smith 
J.A. Smith
</code></pre>

<p>Let me show you what I have tried so far. Removing tabs is quite easy:</p>

<pre><code>With Selection
    .Text = Replace(.Text, vbTab, "")
End With
</code></pre>

<p>The same goes for new line characters:</p>

<pre><code>With Selection
    .Text = Replace(.Text, vbCrLf, ",")
End With
</code></pre>

<p>Unfortunately, it fails to work when I try to remove two new line characters with <code>.Text = Replace(.Text, vbCrLf &amp; vbCrLf, "")</code>
I also tried the following code but it fails to work either.</p>

<pre><code>With Selection
    Do While InStr(1, .Text, vbCrLf &amp; vbCrLf)
        .Text = Replace(.Text, vbCrLf &amp; vbCrLf, vbCrlF)
    Loop
End With
</code></pre>

<p>I came up with another piece of code. I almost does the trick, ie. removes tabs,  both leading and trailing spaces, and more than two spaces. But it also removes <em>all</em> new line characters and I would like to remove only duplicated new line characters (i.e. more than one). Regex <code>\p{2,}</code> nor <code>\n</code> does not work here. It would be also great to remove empty lines.</p>

<pre><code>Sub test()
    With Selection
        Dim RegEx As Object
        Set RegEx = CreateObject("VBScript.RegExp")
        RegEx.Global = True
        RegEx.IgnoreCase = True
        RegEx.Pattern = "\s{2,}"
        .Text = Trim(RegEx.Replace(.Text, " "))
    End With
End Sub
</code></pre>