Home > front end >  How to delete MS Word document pages using Excel VBA?
How to delete MS Word document pages using Excel VBA?

Time:12-30

I have a list of pages that I want to delete in MS Word such as Page number : 5 to 10 , 12 to 16 etc. through MS Excel VBA. I found a code to delete continuous pages through MS Excel VBA but when I run it gives "The Requested member of the collection does not exist" error." How can it be resolved ?

Sub DeletePages()

Dim WordApp As Word.Application
Dim myDoc As Word.Document

' Open the Word document
Set WordApp = New Word.Application
Set myDoc = WordApp.Documents.Open("C:\mydocument.docx")

' Delete pages 3 to 5
myDoc.Range(Start:=myDoc.Bookmarks("Page3").Range.Start, _
            End:=myDoc.Bookmarks("Page5").Range.End).Delete

'Unbind
Set WordApp = Nothing

End Sub


CodePudding user response:

For example:

Sub Demo()
Dim wdApp As New Word.Application, wdDoc As Word.Document, i As Long
With wdApp
  .Visible = False
  .DisplayAlerts = wdAlertsNone
  Set wdDoc = .Documents.Open(FileName:="C:\mydocument.docx", AddToRecentFiles:=False, ReadOnly:=True, Visible:=False)
  With wdDoc
    For i = .ComputeStatistics(wdStatisticPages) To 1 Step -1
      Select Case i
        Case 5 To 10, 12 To 16
          .Range.GoTo(What:=wdGoToPage, Name:=i).GoTo(What:=wdGoToBookmark, Name:="\page").Delete
      End Select
    Next
    .Close SaveChanges:=True
  End With
  .DisplayAlerts = wdAlertsAll
  .Quit
End With
Set wdDoc = Nothing: Set wdApp = Nothing
End Sub

To understand why you don't need to create any bookmarks - and to understand what the code is doing - see:

https://learn.microsoft.com/en-us/office/vba/word/concepts/miscellaneous/predefined-bookmarks

  • Related