Insert page break before search string

J

James Houston

Using Word 97, I'm trying to insert a page break in a document that uses a
string of "=" characters to indicate the start of a new record. What I want
the macro to do is insert a page break before the "=". Here's the macro:

Sub SetPageBreak()
'
' SetPageBreak Macro
' Macro recorded 06/01/04 by James D. Houston
'
Dim iBreakCount As Integer
Dim iLen As Integer
Dim sText As String
Dim myRange As Range

sText =
"======================================================================"
Set myRange = ActiveDocument.Content
myRange.Start = 0
Do While Not myRange.End
myRange.Find.Execute
findtext:="=================================================================
=====", Forward:=True
iLen = Len(sText)
If myRange.Find.Found = True Then
iBreakCount = iBreakCount + 1
If iBreakCount = 1 Then
'do nothing
Else
With myRange
.Collapse direction:=wdCollapseEnd
.InsertBreak wdPageBreak
End With
End If
Else
MsgBox "Done" & " " & iBreakCount & " orders found"
Exit Sub
End If
Loop
End Sub

if I omit the .Collapse method, the page break overwrites the "=" string.
If I change the direction parameter to wdCollapseStart, it inserts an
infinite number of page breaks. How do I Word to insert the page break
before the string?

Any help would be greatly appriciated.

Best,

Jim
 
C

Charles Kenyon

I would create a style that has page-break before as a part of its paragraph
formatting and use the replace function to replace your "sText" with "sText"
formatted using that style. Manual page breaks should be avoided where
possible.
 
D

Doug Robbins - Word MVP

Hi James,

Use the following:

Dim myrange As Range, iBreakCount As Long
iBreakCount = 0
Selection.HomeKey wdStory
Selection.Find.ClearFormatting
With Selection.Find
Do While
..Execute(FindText:="========================================================
==============", MatchWildcards:=False, Wrap:=wdFindStop, Forward:=True) =
True
iBreakCount = iBreakCount + 1
Set myrange = Selection.Range
myrange.Collapse wdCollapseStart
myrange.InsertBreak
Selection.Collapse wdCollapseEnd
Loop
End With
MsgBox "Done" & " " & iBreakCount & " orders found"

Note that Do While .Execute thru = True is a single command and needs to be
all on one line or have VBA linebreak characters properly inserted into it.

--
Please post any further questions or followup to the newsgroups for the
benefit of others who may be interested. Unsolicited questions forwarded
directly to me will only be answered on a paid consulting basis.

Hope this helps
Doug Robbins - Word MVP
 

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