简体   繁体   中英

How do delete an specific page in a word document using Excel VBA?

I'm using Excel VBA to create and populate a word document and I'd like to delete a specific page in that document. I tried the following approach for deleting:

With wDoc
    .GoTo What:=wdGoToPage, Which:=wdGoToAbsolute, Name:="20" 'Page number
    .Bookmarks("\Page").Select
    With Selection
      .Delete
    End With
End With

This code doesn't return any error message on execution but the word page content isn't deleted as expected. What am I missing?

Check below code. I have removed quotes from name parameter here (replaced "20" with 20) You can use your document reference wDoc instead of Activedocument that I have used.

With ActiveDocument
    .GoTo What:=wdGoToPage, Which:=wdGoToAbsolute, Name:=20 'Page number
    .Bookmarks("\Page").Select
    With Selection
      .Delete
    End With
End With

Sometimes you need to keep deleting until the page itself is fully gone.

Sub DeletePage(iPageNumber As Integer)
'
' DeletePage Macro
'

With ThisDocument
    .GoTo(What:=wdGoToPage, name:=iPageNumber).Select
    .Bookmarks("\Page").Range.Select
End With

Selection.Delete

' keep deleting until page is gone
Do
    Selection.MoveLeft Extend:=wdExtend
    Selection.Delete

Loop Until Selection.Information(wdActiveEndAdjustedPageNumber) < iPageNumber

End Sub

With wdDoc
    Lr = .Goto(wdGoToPage, wdGoToLast).Start
    .Range(Lr - 1, wdDoc.Range.End).Delete
End with

Or

wdDoc.Range(wdDoc.Goto(wdGoToPage, wdGoToLast).Start - 1, wdDoc.Range.End).Delete

It will find the last Character/Rage and Delete

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