PDA

View Full Version : Find first word of a paragraph



steve
11-07-2006, 08:13 AM
Hi

Is there anyway of being able to find the first word of a paragraph?

I need to setup a macro that will change the first letter of the first word in every paragraph, but i'm having trouble being able to find the first word of the paragraph!

Any idea please??


Thanks
Steve

fumei
11-07-2006, 10:21 AM
This is easy. It will help you get further if you can think of objects when you code.

Paragraphs are objects. Every document has a collection of these - the Paragraphs collection. If you declare a Paragraph object, you can go through the collection, performing action on every one.Dim oPara As Word.Paragraph
For Each oPara In ActiveDocument.Paragraphs
....do stuff on each paragraph
Next oParaNo need to do any movement, or selection, etc.

However, and I can not stress this enough, it WILL action on every paragraph. So if you are one of those who use the Enter key to put spaces between paragraphs....then each one of those spaces IS a paragraph...and will be actioned.
Sub FirstWord()
Dim strFirstWord As String
Dim strIn As String
Dim oPara As Word.Paragraph
strIn = InputBox("Replacement string?")
For Each oPara In ActiveDocument.Paragraphs
strFirstWord = oPara.Range.Words(1).Text
strFirstWord = strIn & Right(strFirstWord, _
Len(strFirstWord) - 1)
oPara.Range.Words(1).Text = strFirstWord
Next
End SubIf this is a problem - you are using the Enter key to put spaces between paragraphs, then you can:

1. Don't do that. Use Styles to make the space between paragraphs.

2. Change the code to action the paragraphs within a Selection (instead of the whole document). Then make a Selection and run the code.

Oh, and I put the code to get the input string from an Inputbox. It uses that string to replace the first letter. So it would do the same whether you entered "B", or "Blah".

Of course you could put error trapping on that input to not accept anything longer than one character.