Removing Trailing Spaces

S

Steve D

I'm doing some capitalization processing on the first paragraph in a
document. One process step may result in a trailing space being added to the
last word in the paragraph. I want to remove the trailing space. I've tried
two approaches without success. Can you see what's wrong with these
approaches?

Approach 1:
NumWords is the number of words in the first line; i is a counter that
iterates over all the words in the first paragraph. In other words, if I'm
on the last word, replace it with a RTrim'd word.
If i = NumWords Then .Words(i) = RTrim(.Words(i))

Approach 2:
Instead of Approach #1, just RTrim the entire first paragraph whether
there's a space there or not.
ActiveDocument.Paragraphs(1).Range =
RTrim(ActiveDocument.Paragraphs(1).Range)

TIA, Steve
 
J

Jonathan West

Hi Steve

This will remove trailing spaces from all paragraphs in the document

With ActiveDocument.Range.Find
.Format = False
.Text = "^w^p"
.Replacement.Text = "^p"
.Execute Replace:=wdReplaceAll
End With.
 
S

Steve D

Thanks, Jonathon. I had to laugh because that's what I use elsewhere on
clean up the entire doc.
 
S

Steve D

By the way, what was wrong with the techniques I posted? I'd like to
understand why they don't work.

Steve
 
J

Jonathan West

Steve D said:
By the way, what was wrong with the techniques I posted? I'd like to
understand why they don't work.


Approach #1 didn't work because the last Word of a paragraph is the
paragraph mark itself.

Approach #2 didn't work because the entire text of the paragraph includes
the closing paragraph mark after the last space, and so RTrim doesn't trim
anything
 
G

Greg

Jonathan,

I noticed that this method will add an empty paragraph at the end of
the document if the original document has trailing spaces in the last
paragraph. I made a slight modification to ensure its removal:

Sub ScratchMacro()
With ActiveDocument.Range.Find
.Format = False
.Text = "^w^p"
.Replacement.Text = "^p"
.Execute Replace:=wdReplaceAll
End With
Do While ActiveDocument.Paragraphs.Last.Range.Characters.Count = 1
ActiveDocument.Paragraphs.Last.Range.Delete
Loop
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top