Remove trailing whitespace at the end of table cells
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
Next
Next
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...
I use a modification of Tim Pietzcker's Sub, where I use combination of Left() and Trim() instead of regExp (and also use the ActiveDocument instead of ThisDocument):
Sub TrimCellSpaces()
Dim itable As Table
Dim C As Cell
For Each itable In ActiveDocument.Tables
For Each C In itable.Range.Cells
C.Range.Text = Trim(Left(C.Range.Text, Len(C.Range.Text) - 2))
Next
Next
End Sub