0

I am new to the world of coding. I am trying to create a macro to duplicate a specific page for "N" a number of times. The code duplicates the entire document, hope someone could help me fix this issue. Thanks in advance.

Sub DuplicatePage()
Dim numOfCopies As Integer
Dim pageNumber As Integer
Dim i As Integer
'Ask user to enter the number of times to duplicate the page
numOfCopies = InputBox("Enter the number of copies you want to make:")
'Ask the user to enter the page number to duplicate
pageNumber = InputBox("Enter the page number to duplicate:")
'Activate the document
ActiveDocument.Activate
'Check if the entered page number is valid
If pageNumber > ActiveDocument.ComputeStatistics(wdStatisticPages) Then
    MsgBox "The entered page number is greater than the total number of pages in the document. Please enter a valid page number."
    Exit Sub
End If
'Select the page to be duplicated
ActiveWindow.Selection.GoTo What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=pageNumber
Selection.Extend
Selection.Copy
'Duplicate the selected page for the number of times specified by the user
For i = 1 To numOfCopies
    Selection.InsertBreak Type:=wdPageBreak
    Selection.PasteAndFormat (wdFormatOriginalFormatting)
Next i

End Sub

macropod
  • 12,757
  • 2
  • 9
  • 21

1 Answers1

0

For example:

Sub DuplicatePage()
Dim c As Long, p As Long, i As Long, RngSrc As Range, RngTgt As Range
'Ask user to enter the number of times to duplicate the page
c = InputBox("Enter the number of copies you want to make:")
'Ask the user to enter the page number to duplicate
p = InputBox("Enter the page number to duplicate:")
With ActiveDocument
  'Check if the entered page number is valid
  If p > .ComputeStatistics(wdStatisticPages) Then
    MsgBox "The entered page number is greater than the total number of pages in the document. Please enter a valid page number."
    Exit Sub
  End If
  'Select the page to be duplicated
  Set RngSrc = .Range.GoTo(What:=wdGoToPage, Name:=p).GoTo(What:=wdGoToBookmark, Name:="\page")
  With RngSrc
    .Characters.Last.InsertBreak Type:=wdPageBreak
    .MoveEndUntil Chr(12), wdForward
    .End = RngSrc.End + 1
    Set RngTgt = .Duplicate
  End With
End With
'Duplicate the selected page for the number of times specified by the user
For i = 1 To c
    RngTgt.Collapse wdCollapseEnd
    RngTgt.FormattedText = RngSrc.FormattedText
Next i
End Sub
macropod
  • 12,757
  • 2
  • 9
  • 21