Add numpages right after the word Pages

SmallFry
StarLounger
Posts: 91
Joined: 02 Sep 2018, 23:12

Add numpages right after the word Pages

Post by SmallFry »

In my document, there is only one instance of "Pages:" which is followed by two spaces and then the manually input number of pages.

So it looks like, Pages: 39

I would like to run a macro to replace the numbers with a quick part field, NumPages.

I found the below, but since there is only one instance of Pages:, does it need the loop and just not sure how to replace the number with the numpages field.

Code: Select all

Sub FindWord()
    Dim rng As Word.Range
    Dim SearchString As String
    
    Set rng = ActiveDocument.Content
    SearchString = "Pages:"
    With rng.Find
        Do While .Execute(findText:=SearchString, Forward:=True) = True
          rng.MoveEndUntil (" .,;!")
          rng.Select
          rng.Collapse wdCollapseEnd
        Loop
    End With
End Sub

User avatar
HansV
Administrator
Posts: 78408
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Add numpages right after the word Pages

Post by HansV »

A (somewhat belated) welcome to Eileen's Lounge!

Try this version:

Code: Select all

Sub FindWord()
    Selection.HomeKey Unit:=wdStory
    With Selection.Find
       .ClearFormatting
       .MatchWildcards = True
       .Text = "Pages:  [0-9]{1,}"
       .Execute
    End With
    Selection.Collapse Direction:=wdCollapseEnd
    Selection.MoveStartWhile Cset:="0123456789", Count:=wdBackward
    ActiveDocument.Fields.Add Range:=Selection.Range, Type:=wdFieldNumPages
End Sub
Best wishes,
Hans

SmallFry
StarLounger
Posts: 91
Joined: 02 Sep 2018, 23:12

Re: Add numpages right after the word Pages

Post by SmallFry »

Hi Hans,

That is wonderful. Thank you very much.