Selectively delete Word pages with VBA depending on content

my word document has page breaks so pages are easily identified.  I need to either delete pages with nominated text OR only include pages with nominated text.   After I have page with the correct title (not shown in example below), I have to either keep or delete it, depending on the action parameter.  This code needs to be in a template as new word documents have to be processed each day (vbs job driven by an excel worksheet).
Any help will be greatly appreciated!


Sub SearchPage(pagenum)

' action is I to include or E to exclude

Dim r As Range
Dim found As Boolean
Dim newpage As Integer
found = True
   
    Selection.Find.ClearFormatting
    MsgBox Selection.Text
    With Selection.Find
        .Text = mtext
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchAllWordForms = False
        .MatchSoundsLike = False
        .MatchWildcards = True
    End With
   
    If Selection.Find.Execute Then
    'MsgBox "found"
        newpage = Selection.Information(wdActiveEndPageNumber)
        MsgBox pagenum & " " & newpage
        If newpage = pagenum Then
            If maction = "E" Then
                Selection.Bookmarks("\Page").Range.Delete
                rcount = rcount + 1
               
            End If
         End If
     Else
        If maction = "I" Then
           Selection.Bookmarks("\Page").Range.Delete
           rcount = rcount + 1
        End If
     End If
   
 
End Sub
LVL 1
chris_desboroughAsked:
Who is Participating?
 
chris_desboroughConnect With a Mentor Author Commented:
The looping was caused by the fact that the search started again at page 1 after reaching the end of the document.  I thought it would end.  Once I catered for this, it is working fine.  Sorry to bother you.
0
 
GrahamSkanRetiredCommented:
The logic of what you need isn't quite clear. Perhaps you should say what goes wrong with the code that you have posted?
0
 
chris_desboroughAuthor Commented:
My code just never ends.  I  have been having difficulty debugging with the code is in a template so I guess I need to suppress the frustration and put the code in my document for debugging.  I will do this and then ask again.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.