Search code examples
vbams-wordfind

Find unique text then note page number


Having used .Find to locate text in a Word document, how can I find out what page this text was found on?

I have a Word document of shipping labels, one per page. I want to search this file for a specific order number and make a note of the filename and page number. This is so that when my app (MS Access using Word Object Library) later dispatches that order to the customer it can automatically open the correct label file and print the label for that order.

Simplified code below. The find is working (Find.Found = True). The code returns the last page of the document. If I run the code with the Word document visible I can see that although the .Find.Execute is working the document is not moving to the correct page.

Dim Find As Word.Find
Dim LabelPageNum as Integer
    
LabelPageNum = 0

Set Find = Word.ActiveDocument.Content.Find
            
Find.ClearFormatting
Find.Text = "ABC-123456"
Find.Forward = True
Find.Wrap = wdFindContinue
Find.Format = False
Find.MatchWildcards = True
Find.IgnoreSpace = True
Find.IgnorePunct = True
Find.Execute
            
If Find.Found Then
    LabelPageNum = Word.ActiveDocument.Content.Information(wdActiveEndPageNumber)
End if

Solution

  • Find.Parent.Information(wdActiveEndPageNumber) will give you the result. Find.Parent returns the range that has been found - and on that you apply Information.

    BTW: It's good coding practice to not use code words as variable names