Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find unique text then note page number

Tags:

find

ms-word

vba

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
like image 372
SteveB Avatar asked Oct 18 '25 17:10

SteveB


1 Answers

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

like image 88
Ike Avatar answered Oct 20 '25 16:10

Ike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!