Find and replace only on page 1

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

Find and replace only on page 1

Post by SmallFry »

In this VBA to f/r, can it be limited to only page 1? I have move than one space after somebodies middle initial which I need to reduce to just one space. The names are only on page 1.

Code: Select all

Sub ReduceSpaces()
    With Selection
        .HomeKey Unit:=wdStory
        With .Find
            .ClearFormatting
            .Replacement.ClearFormatting
            .Forward = True
            .Wrap = wdFindContinue
            .Format = False
            .MatchWildcards = True
            .Text = "([A-Z])(.)(  )"
            .Replacement.Text = "\1\2 "
            .Execute Replace:=wdReplaceAll
        End With
    End With
End Sub

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

Re: Find and replace only on page 1

Post by HansV »

I'd do it like this:

Code: Select all

Sub ReduceSpaces()
    Selection.HomeKey Unit:=wdStory
    With ActiveDocument.Bookmarks("\page").Range.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Forward = True
        .Wrap = wdFindStop
        .Format = False
        .MatchWildcards = True
        .Text = "([A-Z].) {2,}"
        .Replacement.Text = "\1 "
        .Execute Replace:=wdReplaceAll
    End With
End Sub
Best wishes,
Hans

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

Re: Find and replace only on page 1

Post by SmallFry »

Thanks Hans. This works great. I'm having trouble finding information on Bookmarks("\page").Range.Find. What is this saying?

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

Re: Find and replace only on page 1

Post by SmallFry »

I found this #3, but how does it know page 1?

https://shaunakelly.com/word/word-devel ... model.html" onclick="window.open(this.href);return false;

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

Re: Find and replace only on page 1

Post by HansV »

\page is one of the pre-defined hidden bookmarks in Word. It refers to the entire page containing (the start of) the selection.

See Predefined Bookmarks for more information and a list of built-in bookmarks.

In the code that I posted, we use Selection.HomeKey Unit:=wdStory to move to the top of the document. This causes \page to refer to the first page.
If we had used Selection.EndKey Unit:=wdStory, \page would have referred to the last page.
Best wishes,
Hans

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

Re: Find and replace only on page 1

Post by SmallFry »

Perfect. Thank you for the extra explanation.