Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Word VBA to compare first words of each successive paragraph 1

Status
Not open for further replies.

VBAjedi

Programmer
Dec 12, 2002
1,197
KH
Hi everyone! Haven't been in here in a while. . . I'm weak on Word VBA (Excel's my thing) and I'm in a time-sensitive bind.

I just need a VBA code frag that will step through the paragraphs of the current document, compare the first word of the current paragraph to the first word of the next paragraph (they are product numbers), and if they are the same, set the following for the current paragraph:

With .ParagraphFormat
.WidowControl = True
.KeepWithNext = True
' or select both paragraphs and set .KeepTogether = True
End With

Basically I need to make sure that successive paragraphs dealing with the same product print on the same page.

Clear as mud?

Thanks for any quick assistance you can give on this! I don't have the time to learn the whole Word object tree for this little project. . .

VBAjedi [swords]
 
A starting point:
Dim p As Integer
For p = 1 To ActiveDocument.Paragraphs.Count - 1
With ActiveDocument.Paragraphs(p).Range
If Trim(.Words(1).Text) = Trim(ActiveDocument.Paragraphs(p + 1).Range.Words(1).Text) Then
With .ParagraphFormat
.WidowControl = True
.KeepWithNext = True
End With
End If
End With
Next

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
PHV,

Greetings from Liberia, West Africa (do I have the distinction of being the only guy you know in Liberia?)!

Your code frag is MUCH nicer than my little hacked approach. . . I felt like I did when I was learning Excel VBA what with fixed-sized loops and selection changes:

For a = 1 To 5000
x = Selection.Words(1).Text
Selection.MoveDown Unit:=wdParagraph, Count:=1
y = Selection.Words(1).Text
If x <> y Then
Selection.MoveUp Unit:=wdParagraph, Count:=1
With Selection.ParagraphFormat
.WidowControl = True
.KeepWithNext = True
End With
Selection.MoveDown Unit:=wdParagraph, Count:=1
End If
Next a

Have a star for giving me a little light!

VBAjedi [swords]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top