Word – Remove trailing whitespace at the end of table cells

find and replacemicrosoft wordregex

I have opened a PDF file in Word in order to edit it (the original Word document is lost). During the conversion, each line of text and each table cell was given an extra space. Of course, they don't really hurt anyone except me and my slight OCD. I don't like trailing whitespace.


It's trivial to remove a trailing space at the end of a line (search for " ^p" and replace with "^p"), but there doesn't seem to be a special character for "end of table cell marker" in the find/replace dialog, and the Word "regex" engine doesn't appear to support anchors either.

A Google search brought me to this tip on how to add something to the end of a table cell (I planned to add something like "§§§" to each cell and then do a simple search/replace for " §§§"), but in Word 2016, I can't find the Style "Table cell", at least not in the German version of Word.

Any other idea I could try? Also, any idea how to remove one or more spaces at the end of a line/table cell? Quantifiers don't seem to work in a non-regex find/replace.

Best Answer

  • OK, I've been digging around the Word VBA object model and came up with this (Microsoft VBScript Regular Expressions 5.5 enabled):

    Sub TrimCellSpaces()
        Dim myRE As New RegExp
        Dim itable As Table
        Dim C As Cell
        myRE.Pattern = "\s+(?!.*\w)"
        For Each itable In ThisDocument.Tables
            For Each C In itable.Range.Cells
                With myRE
                    C.Range.Text = .Replace(C.Range.Text, "")
                End With
    End Sub

    Interestingly enough, my inital attempt (using Trim(C.Range.Text)) didn't remove the spaces, on the contrary, it added a paragraph marker at the end of each cell. Puzzled by this, I tried a regex \s+$ with the same results. Inspecting the local object tree, I found that a cell that contained the text Note  actually contained Note \x0d\x0d\x07 (I have since found out why this is the case). That's why I had to use that weird regex to find the last spaces in a cell...

  • Related Question