VBA Help

T

TJ

Our mainframe formats some of our reports to have multiple reports in one
file end-to-end. Each report begins with SAM5XXX. I would like to put a
page break at each instance of SAM5. The below macro works, but it puts a
blank page at the beginning of the document, thus the two lines after the
"Loop".

Can anyone suggest how to clean up the code to it does not put a blank page
at the beginning?

Thanks for your help!


Sub SAM5_PageBreak()
'
'
'
With ActiveDocument.Content.Find
.ClearFormatting
Selection.MoveDown Unit:=wdLine, Count:=2
Do While .Execute(FindText:="SAM5", Forward:=True, Format:=False) =True
With Selection.Find
.Forward = True
.ClearFormatting
.MatchWholeWord = False
.MatchCase = False
.Wrap = wdFindContinue
.Execute FindText:="SAM5"
Selection.MoveLeft Unit:=wdCharacter, Count:=1
Selection.InsertBreak Type:=wdPageBreak
Selection.MoveDown Unit:=wdLine, Count:=2
End With
Loop
Selection.HomeKey Unit:=wdStory
Selection.Delete Unit:=wdCharacter, Count:=1
End With
End Sub
 
P

Peter Hewett

Hi TJ

This may be somewhat more efficient even if there's somewhat more code.
Some of the extra code arrises because I've split up your execute
statement, reset a couple more .Find properties and variable declarations.

It finds SAM5 followed by 4 characters it wont match SAM5abc, but will
match SAM5abcd, or SAM5ABCD or SAM50001.

Sub SAndR()
Dim rngReplace As Word.Range
Dim rngFound As Word.Range
Dim lngCount As Long

Set rngReplace = ActiveDocument.Content
With rngReplace.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "SAM5?{4}"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True

' Find all occurrences in the document
Do While .Execute
lngCount = lngCount + 1

' Insert a section break if this is not the first occurrence
If lngCount > 1 Then
Set rngFound = rngReplace.Duplicate
rngFound.InsertBreak wdSectionBreakNextPage
End If

' Setup range to continue the search after the
' text that we just found
rngReplace.Collapse wdCollapseEnd
Loop
End With
End Sub

HTH + Cheers - Peter
 

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

Similar Threads


Top