简体   繁体   中英

How to delete MS Word document pages using Excel VBA?

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


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM