如何使用Excel VBA删除MS Word文档页面?

qojgxg4l  于 2023-01-03  发布在  其他
关注(0)|答案(1)|浏览(195)

我有一个要在MS Word中删除的页面列表,如页码:5到10,12到16等。我发现了一个代码,通过MS Excel VBA删除连续页面,但当我运行它给出***“集合的请求成员不存在”错误。***如何解决它?

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
pod7payv

pod7payv1#

例如:

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

要了解为什么不需要创建任何书签,以及代码的作用,请参见:
https://learn.microsoft.com/en-us/office/vba/word/concepts/miscellaneous/predefined-bookmarks

相关问题