Home > Mobile >  VBA Word - Find unique text then note page number
VBA Word - Find unique text then note page number

Time:07-07

TLDR: having successfully used a .FIND object to locate some text in a Word document, how can I find out what page this text was found on?

Longer explanation: 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.

Here is my (simplified) code below. The find is working (Find.Found = True) but I am struggling to work out how to detect the page number. The code shown always 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

CodePudding user response:

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

CodePudding user response:

If Find.Found Then LabelPageNum = .Information(wdActiveEndPageNumber)
  • Related