VBA code to delete a page in a Word doc

C

cyberdude

Hi,

I am using Word 2003. May I ask how to write a VBA code to delete a
certain page in a Word document? Thank you.

Mike
 
G

Graham Mayor

'Page' is a vague concept in Word, which is not a page layout application.
The nearest you will achieve is

Sub PageDelete()
On Error Resume Next
ActiveDocument.Bookmarks("\page").Range.Delete
End Sub


which will delete the current 'page'.


--
<>>< ><<> ><<> <>>< ><<> <>>< <>><<>
Graham Mayor - Word MVP


<>>< ><<> ><<> <>>< ><<> <>>< <>><<>
 
G

Greg Maxey

As Graham states "page" in Word is a vague concept. See:
http://daiya.mvps.org/wordpages.htm

That said, and using Word2003 or later, there are some things that you can
use in addition to the builtin bookmark "\page" that might suit your need.
They are the Panes, Pages, and Rectangle collections primarily used for
defining page setup.

The following example code was tested on a very simple four page document
with text, headers, footers, and a few shapes. It worked, but as you can
see there are a lot of "ifs" involved so it may be more trouble to set up
that it is worth.

Part of the problem is figuring out which rectangle to delete. If you
delete the "header" or "footer" rectangle then all the headers in the other
pages are gone as well :-(. I haven't done any serious testing with these
methods so I don't know what would happen if you delete the maintext
rectangle of a page that is uniquen (i.e., one page lone with different
header and footer than all the other pages.)

Sub DeletePage()
Dim MyPane As Pane
Dim MyPage As Page
Dim i As Long
Dim lngUserView As Long
lngUserView = Application.ActiveWindow.View.Type
Set MyPane = ActiveWindow.ActivePane
On Error GoTo Err_Handler
Set MyPage = MyPane.Pages(InputBox("Enter the page to delete: "))
For i = 1 To MyPage.Rectangles.Count
If MyPage.Rectangles(i).RectangleType = wdTextRectangle Then
If MyPage.Rectangles(i).Range.StoryType = wdMainTextStory Then
MyPage.Rectangles(i).Range.Delete
End If
End If
Next i
If Application.ActiveWindow.View.Type <> lngUserView Then
Application.ActiveWindow.View.Type = lngUserView
End If
Exit Sub
Err_Handler:
If Err.Number = 5894 Then
Application.ActiveWindow.View.Type = wdPrintView
Resume
End If
End Sub




--
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Greg Maxey - Word MVP

My web site http://gregmaxey.mvps.org
Word MVP web site http://word.mvps.org~~~~~~~~~~~~~~~~~~~~~~~~~~
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top