Help with Word VBA - Replacing text in TextBox

CNorth

New Member
Joined
Jan 7, 2021
Messages
24
Office Version
  1. 365
Platform
  1. Windows
Hi

I am trying to insert page numbers into TextBoxes in the document header in the format Page X of Y. Unfortunately, I cannot just use insert page numbering via the headers (or footers) as the document already contains a header that must remain as is and the TextBoxes must be positioned above it. Anyway, I decided to insert the string "Page X of " and use a counter to replace X. When testing the Sub below, I run into an error on the line
VBA Code:
For Each counter In Selection.Range
I'd really appreciate any help to correct this.

VBA Code:
Sub ReplaceInTextBox()

Dim shp As Shape
Dim counter As Long

 Selection.HomeKey Unit:=wdStory

a = ActiveDocument.BuiltInDocumentProperties("Number of Pages")
For i = 1 To a

Dim Box1 As Shape
    Set Box1 = ActiveDocument.Shapes.AddTextbox( _
    Orientation:=msoTextOrientationHorizontal, _
        Left:=65, Top:=1, Width:=150, Height:=30)
   
Box1.TextFrame.TextRange.Text = ActiveDocument.Name & Chr(10) & "Page X of " & a

  
counter = 0

  For Each shp In ActiveDocument.Shapes
        Selection.Select
            For Each counter In Selection.Range
            counter = counter + 1
            Next counter
  Next

   Selection.Find.ClearFormatting
   Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "X"
        .Replacement.Text = counter
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = True
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll

Selection.GoTo What:=wdGoToPage, Which:=NextPage

End Sub

Thanks
 

Excel Facts

Excel Can Read to You
Customize Quick Access Toolbar. From All Commands, add Speak Cells or Speak Cells on Enter to QAT. Select cells. Press Speak Cells.
Why do you not use the fields for pagenumber and number of pages?
VBA Code:
    Box1.Select
    Selection.TypeText Text:="Page "
    Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:="PAGE  ", PreserveFormatting:=True
    Selection.TypeText Text:=" of "
    Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:="NUMPAGES  ", PreserveFormatting:=True
 
Upvote 0
Solution
VBA Code:
  For Each shp In ActiveDocument.Shapes
        Selection.Select
            For Each counter In Selection.Range
            counter = counter + 1
            Next counter
  Next

Replace with:
VBA Code:
counter = ActiveDocument.Shapes.Count
 
Upvote 0
Thank you for your help. Adding fields worked. I also tried the code below to avoid the use of Selection but it generated an error with the counter variable stating the object was nothing.

VBA Code:
counter = ActiveDocument.Shapes.Count
 
Upvote 0
Strange. When the macro have one textbox added the line: ActiveDocument.Shapes.Count should be 1.
 
Upvote 0
Better, IMHO:
VBA Code:
Sub AddPgNums()
Application.ScreenUpdating = False
Dim HdFt As HeaderFooter, Rng As Range, Tbl As Table
'Each Section in a Word document has 3 header & footer objects - primary, first page & even page
For Each HdFt In ActiveDocument.Sections(1).Headers
  With HdFt
  'Update each header that is being used in this document
    If .Exists = True Then
      Set Rng = .Range
      Rng.Collapse wdCollapseStart
      'Create a 2*1 table
      Set Tbl = Rng.Tables.Add(Range:=Rng, NumRows:=1, NumColumns:=2, _
        DefaultTableBehavior:=wdWord8TableBehavior, AutoFitBehavior:=wdAutoFitFixed)
        'Position, size, & format the table
      With Tbl
        With .Rows
          .WrapAroundText = True
          .RelativeVerticalPosition = wdRelativeVerticalPositionPage
          .VerticalPosition = InchesToPoints(0.25)
          .RelativeHorizontalPosition = wdRelativeHorizontalPositionMargin
          .HorizontalPosition = wdTableRight
        End With
        With .Rows(1)
          .HeightRule = wdRowHeightExactly
          .Height = InchesToPoints(0.25)
          .Cells.VerticalAlignment = wdCellAlignVerticalCenter
          With .Range.ParagraphFormat
            .SpaceBefore = 0
            .SpaceAfter = 0
          End With
        End With
        .Columns(1).Width = InchesToPoints(2)
        .Columns(2).Width = InchesToPoints(1)
        .Borders.Enable = False
        'Add a FILENAME field to the first cell
        Set Rng = .Cell(1, 1).Range
        With Rng
          .ParagraphFormat.Alignment = wdAlignParagraphLeft
          .End = .End - 1
          .Fields.Add Range:=.Duplicate, Type:=wdFieldEmpty, Text:="FILENAME", PreserveFormatting:=False
        End With
        'Add 'Page X of Y' text & corresponding PAGE & NUMPAGES fields to the second cell
        Set Rng = .Cell(1, 2).Range
        With Rng
          .ParagraphFormat.Alignment = wdAlignParagraphRight
          .End = .End - 1
          .Text = "Page X of Y"
          .Fields.Add Range:=.Characters.Last, Type:=wdFieldEmpty, Text:="NUMPAGES", PreserveFormatting:=False
          .Fields.Add Range:=.Characters(6), Type:=wdFieldEmpty, Text:="PAGE", PreserveFormatting:=False
        End With
      End With
    End If
  End With
Next
End Sub
Note that nothing is ever selected.

You may need to adjust the table position & cell sizes to suit the specifics of your document.
 
Upvote 0

Forum statistics

Threads
1,224,820
Messages
6,181,157
Members
453,021
Latest member
Justyna P

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top