0

I have a Word template (1 page document) that merges several documents into the template. I need assistance with getting a code for deleting every page except the front page (first page). Every time the macro runs, it adds additional documents to the template, so the length of the document varies depending on which documents are merged.

So if I re-run the macro, I want it to delete every page in the document except the first page every time the macro runs.

I've tried to rewrite and adjust the following code, but it does not work fully and leaves a blank second page.

    Dim rgePages As Range
    Dim PageCount As Integer
    PageCount = ActiveDocument.ComputeStatistics(wdStatisticPages)
    Selection.GoTo What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=2
    Set rgePages = Selection.Range
    Selection.GoTo What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=PageCount
    rgePages.End = Selection.Bookmarks("\Page").Range.End
    rgePages.Delete

I want the macro to delete every page independent of the length of the document and ensure that only the front page is left.

Oscar Sun
  • 1,427
  • 2
  • 8
  • 13
zz5zz
  • 1
  • 1

1 Answers1

0

So how about this?

Sub Word_VBA_delete_every_page_except_the_front_page()

    Dim d As Word.Document

    Dim rgePages As Range

    Rem no use here
    'Dim PageCount As Integer
    'PageCount = ActiveDocument.ComputeStatistics(wdStatisticPages)
    
    Set d = ActiveDocument: Set rgePages = d.Range '.Characters(1)
    
    Rem no use here
    'PageCount = d.ComputeStatistics(wdStatisticPages)
    
    'Selection.GoTo What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=2
'    Set rgePages = Selection.Range
'    Selection.GoTo What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=PageCount
'    rgePages.End = Selection.Bookmarks("\Page").Range.End

    Set rgePages = rgePages.GoTo(What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=2)
    
    rgePages.SetRange rgePages.Previous.End, d.Range.End
    
    rgePages.Delete

End Sub
Oscar Sun
  • 1,427
  • 2
  • 8
  • 13