I need VBA code to delete all sections(pages) except first in Word document
For this I use below code.
For Each oSec In ActiveDocument.Sections
If oSec.Index <> 1 Then
oSec.Range.Delete
End If
Next oSec
This works but does not delete second section only removes its content.
If I removes if condition in code it removes content of first page.
I want to preserve content of first page.
Please tell me where I am making mistake.
Matt
44.3k8 gold badges77 silver badges115 bronze badges
asked Feb 26, 2014 at 5:25
When deleting you need to include section break marks. Try to change this line:
oSec.Range.Delete
into this one:
ActiveDocument.Range(oSec.Range.Start - 1, oSec.Range.End).Delete
BTW, you should not think that page=section, they are different type of document units.
answered Feb 26, 2014 at 7:05
Kazimierz JaworKazimierz Jawor
18.8k7 gold badges35 silver badges55 bronze badges
2
- Remove From My Forums
-
Question
-
I am trying to code a macro that will select all the text/pages from page 2 to the end of the document, and delete it, leaving the cursor in the home position on pg 2. I have this code which will delete only page 2.
I am stuck, please help!
‘Selection.GoTo wdGoToPage, wdGoToAbsolute, 2
‘ActiveDocument.Bookmarks(«page»).Range.DeleteI works perfectly, but only clears the 2nd page. I need it to be able to clear all pages from page 2 to the
end of the document.Thanks, Sean
Answers
-
Hi,
Based on my understanding, you want to clear all pages from specified page index to last page of the document. You can use the
Range.End to set the end of the region.
Here is a sample code for you reference:
Sub Clearpages() Dim rgePages As Range Dim PageCount As Integer PageCount = ActiveDocument.ComputeStatistics(wdStatisticPages) Selection.GoTo What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=2 Set rgePages = Selection.Range Selection.GoTo What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=PageCount rgePages.End = Selection.Bookmarks("Page").Range.End rgePages.Delete End Sub
Regards,
Marvin
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey.-
Proposed as answer by
Saturday, April 12, 2014 3:14 PM
-
Marked as answer by
glyder50
Monday, April 14, 2014 1:06 PM
-
Proposed as answer by
-
Thank you Marvin! It works, exactly as I need it too! Much appreciated.
SEan
-
Marked as answer by
glyder50
Monday, April 14, 2014 1:07 PM
-
Marked as answer by
1 / 1 / 0
Регистрация: 03.11.2018
Сообщений: 12
1
Word
Удаление страниц в документе
04.11.2018, 16:14. Показов 4835. Ответов 1
Добрый день!
Проблема следующая:
Есть туча файлов, в которых нужно удалить первые две страницы.
Шарил по просторам и нашел следующие виды макросов
Пакетное форматирование:
Кликните здесь для просмотра всего текста
Visual Basic | ||
|
И, непосредственно, сам макрос удаления страниц
Кликните здесь для просмотра всего текста
Visual Basic | ||
|
Бьюсь над совокуплением оных! Но все равно не получается. Будьте добры, подскажите, как это сделать.
0
If you work with long Microsoft Word documents and frequently have to delete pages, you’ll appreciate this simple VBA procedure.
Deleting a page in a Microsoft Word document isn’t difficult, but there’s no quick-click route. You must delete the content and the soft or hard page break. It’s a bit awkward. You probably don’t mind doing so occasionally, but if you have to do this a lot, you might find doing so tedious. In this article, I’ll show you two VBA procedures that will delete the current page. In addition, I’ll show you how to assign a keyboard shortcut to the procedure so you can execute it quickly. Even if you don’t need the procedure, you can learn how to create a keyboard shortcut.
SEE: Windows 10: Lists of vocal commands for speech recognition and dictation (free PDF) (TechRepublic)
I’m using Microsoft 365 on a Windows 10 64-bit system, but you can use earlier versions. Word Online doesn’t support VBA. For your convenience, you can download the demonstration .docm, .doc and .cls files.
How to use the VBA procedure
You might be surprised how short the procedure needed to delete the current page is. It’s only one line, thanks to a system-defined bookmark, Page, which refers to the current page. Listing A shows the simple procedure. (You’ll often see the terms macro and sub procedure used interchangeable, and that’s OK.)
Listing A
Sub DeleteCurrentPage()
‘Run procedure to delete the current page.
‘Keyboard shortcut Alt + d.
ActiveDocument.Bookmarks(“Page”).Range.Delete
End Sub
As mentioned, the Page bookmark is a special reference to the current page. The Range property specifies the page and the Delete method deletes it. If you omit the Range property, the statement returns an error because VBA attempts to delete the Page bookmark; you can’t delete it or modify it because it’s read-only. To delete a bookmark, you would reference it by name and omit the Range property.
The procedure has two limitations:
- It won’t delete contiguous pages. If you select multiple contiguous pages, the procedure deletes the first page in the grouping.
- It won’t delete the last page. It will delete the contents of the last page, but it won’t delete the page, so you won’t want to run this with the last page selected.
How to add the procedure
If you’re familiar with VBA, you can probably skip this section and move right on to running the macro to see how it works.
To enter the procedure, press Alt + F11 to open the Visual Basic Editor. In the Project Explorer to the left, select ThisWorkbook so you can run the procedure in any sheet. You can enter the code manually or import the downloadable .cls file. In addition, the macro is in the downloadable .docm and .doc files. If you enter the code manually, don’t paste from this web page. Instead, copy the code into a text editor and then paste that code into the ThisWorkbook module. Doing so will remove any phantom web characters that might otherwise cause errors.
If you are using a ribbon version, be sure to save the workbook as a macro-enabled file. If you’re working in the menu version, you can skip this step. Now, let’s run the procedure and see how it works.
How to run the VBA procedure to delete pages in Word
You can use the Developer tab to execute the procedure, but it takes several clicks. Instead, let’s assign a keyboard shortcut to run it:
- Click the Quick Access Toolbar dropdown and choose More Commands.
- In the left pane, click Customize Ribbon.
- Click the Customize button (Figure A) to create the shortcut.
- In the resulting dialog, choose Macros from the Categories list (it’s near the bottom of the list).
- From the Save Changes In dropdown, choose the active document.
- Click inside the Press New Shortcut Key control and hold down the Alt key while you press the d key, for a shortcut combination of Alt + D (Figure B). Before you click Assign, always check Currently Assigned To control. In this case, the combination isn’t in use. When the combination is in use, this control will alert you; you’ll have to decide whether to use a different combination or to write over the current assignment.
- Click Assign, click Close, and then click OK to return to the document.
Figure A
Figure B
Now that you have quick access to the procedure, let’s run it. The demonstration file has five pages, as you can see in Figure C. The header displays page numbers, which will update accordingly when you delete a page. The larger number is actual text, so it’s visually apparent that you really did delete a page. Click on any page but the last one and press Alt + D. As you can see in Figure D, I deleted page 3.
Figure C
Figure D
The procedure in Listing A won’t delete the last page, but it will delete any content on the last page. If you don’t want to have to remember that quirk, you can use Listing B instead. The two integer variables store the current page number and the last page number. When they’re not equal, the current page is deleted. When they’re equal, nothing happens.
Listing B
Sub DeleteCurrentPage()
‘Run procedure to delete the current page.
‘Keyboard shortcut Alt + d.
Dim cur As Integer
Dim last As Integer
cur = Selection.Range.Information(wdActiveEndPageNumber)
last = Selection.Range.Information( _
wdNumberOfPagesInDocument)
‘Compares the current page number and the last page number.
‘When they aren’t equal, delete the current page.
If cur <> last Then
ActiveDocument.Bookmarks(“Page”).Range.Delete
End If
End Sub
Both procedures are simple and probably have a limited audience. However, if you frequently delete pages, either will be useful.
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.
Author Introduction:
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