Share via

Find text and return page number

Anonymous
2013-03-26T20:47:01+00:00

I am trying to build a macro, that will find text in the document and then print the page that the text resides on.

Find Widget1, then if widget1 is on page 2... print page 2.

Find Widget2, then if widget2 is on page 4... print page 4

and so on.

Snippet of the code thus far.  Been hard coding the tofrom range, but rather have it print current page or return the page number.

Set rg = ActiveDocument.Range

    With rg.Find

        ' set up the find parameters

        .Format = True

        .Text = "Widget1"

        .Forward = True

        .Wrap = wdFindStop

    If .Execute Then

        ' exclude the paragraph mark

        rg.MoveEnd wdCharacter, 0

        ' get the text

        output = rg.Text

 'Create and Export page as PDF

 ActiveDocument.ExportAsFixedFormat _

 OutputFileName:=strPathPDF, _

 ExportFormat:=wdExportFormatPDF, _

 OpenAfterExport:=True, _

 OptimizeFor:=wdExportOptimizeForPrint, _

 Range:=wdExportFromTo, _

 From:=1, _                                                                      

 To:=1, _

 Item:=wdExportDocumentContent, _

 IncludeDocProps:=True, _

 KeepIRM:=True, _

 CreateBookmarks:= _

 wdExportCreateNoBookmarks, _

 DocStructureTags:=True, _

 BitmapMissingFonts:=True, _

 UseISO19005_1:=False

End if

End With

....

Microsoft 365 and Office | Word | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments
Answer accepted by question author
  1. Doug Robbins - MVP - Office Apps and Services 322.9K Reputation points MVP Volunteer Moderator
    2013-03-26T22:08:56+00:00

    Use

    Dim p As Long

    Selection.HomeKey wdStory

    Selection.Find.ClearFormatting

    With Selection.Find

        Do While .Execute(FindText:="Widget1", Forward:=True, _

        MatchWildcards:=False, Wrap:=wdFindStop, MatchCase:=True) = True

            p = Selection.Information(wdActiveEndPageNumber)

        Loop

    End With

    ActiveDocument.ExportAsFixedFormat OutputFilename:="expanding", ExportFormat:=wdExportFormatPDF, OpenafterExport:=True, OptimizeFor:=wdExportOptimizeForPrint, Range:=wdExportFromTo, From:=p, To:=p

    2 people found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful