In this article, we will focus on demonstrating you of how to delete multiple pages in your Word document via VBA.
Drafting a document requires adjustments all the time. And deleting pages of contents is just as necessary as other modifications. To remove useless texts is easy. Most people choose to make a selection and then press either “Delete” or “Backspace” shall do the task.
This certainly will get you what you want. But there is a quicker to do so. What’s more, you skip the selection step and delete multiple pages at once. The appealing approach is to run a Word macro.
Delete Current Page
For those who hate to make selection over a range of text, this can be your blessing. First let’s show you how to delete current page via VBA.
- To begin with, put cursor on the page you want to delete.
- Open VBA editor in Word by clicking the “Developer” tab and then the “Visual Basic”. If the “Developer” tab is not yet available in the Ribbon, press “Alt+ F11” instead.
- Secondly, click “Normal”.
- Then click “Insert” and choose “Module” on that menu.
- Open the new module by double click.
- And paste following codes there:
Sub DeleteCurrentPage() Dim objDoc As Document ' Initialize Set objDoc = ActiveDocument ' Delete current page. objDoc.Bookmarks("\Page").Range.Delete End Sub
- Finally, click “Run” button or hit “F5”.
Delete Multiple Pages
- Follow steps above to install and run a macro.
- Replace the macro with this one:
Sub DeletePagesInDoc() Dim objRange As Range Dim strPage As String Dim objDoc As Document Dim nSplitItem As Long Application.ScreenUpdating = False ' Initialize and enter page numbers of pages to be deleted. Set objDoc = ActiveDocument strPage = InputBox("Enter the page numbers of pages to be deleted: " & vbNewLine & _ "use comma to separate numbers", "Delete Pages", "For example: 1,3") nSplitItem = UBound(Split(strPage, ",")) ' Find specified pages and highlight their contents. For nSplitItem = nSplitItem To 0 Step -1 With ActiveDocument Selection.GoTo What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=Split(strPage, ",")(nSplitItem) Set objRange = .Bookmarks("\Page").Range objRange.Delete End With Next nSplitItem Application.ScreenUpdating = True End Sub
- Running macro will trigger an input box. Enter the page number of the pages to be deleted, and use comma to separate them. Don’t enter a space after the comma.
- Then click “OK” to proceed.
Of course, you can use this macro to delete current page. Simply enter the page number.
Don’t Let Corruption Stop You
Once a data disaster happens, it’s sure to slow down your daily work and you have to bear the additional cost as well. To make sure your data is safe and sound, you’d better get hold of a doc damage repairing tool.
Vera Chen is a data recovery expert in DataNumen, Inc., which is the world leader in data recovery technologies, including fix Excel and pdf repair software products. For more information visit www.datanumen.com