I am trying to clean up tables in a rather large Word document. Part of this is removing extra spaces. I have no problems deleting spaces at the start of text, or double spaces in the middle of text, but the very last space in a cell will not be deleted.
Sample code:
ActiveDocument.Tables(1).Cell(1, 1).Range.Characters(ActiveDocument.Tables(1).Cell(1, 1).Range.End - 1).Delete
(note: this code is in a loop to iterate and remove the last space as long as there are spaces at the end of the text in a cell)
This is an example cell with text:
After looping several times I get:
Running the code some more times will not remove that last space. How can I do this?
Constraints: I cannot load the text in a string, shorten it, then reinsert the string in the cell as I then lose some formatting and icons that are inserted in the text.
Here is some more code as requested by Tim:
For Each myTable In ActiveDocument.Tables
For i = 1 To myTable.Rows.Count
For j = 1 To myTable.Columns.Count
Set myCell = myTable.Cell(i, j)
Do
MsgBox "|" & myCell.Range.Characters(myCell.Range.End - 1).Text & "|"
myCell.Range.Characters(myCell.Range.End - 1).Delete
Loop Until myCell.Range.Characters(myCell.Range.End - 1).Text <> " "
Next j
Next i
Next myTable
Warning!: This causes an infinite loop as myCell.Range.Characters(myCell.Range.End - 1).Text
always evaluates to a space -- it's trying to debug this that I found out the last space was not getting deleted.
CodePudding user response:
Sometimes you have to be devious....
Do While ActiveDocument.Tables(1).Cell(1, 1).Range.Characters.Last.Previous = " "
ActiveDocument.Tables(1).Cell(1, 1).Range.Characters.Last.Previous.Text = vbNullString
Loop