Удалить страницы vba word

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's user avatar

Matt

44.3k8 gold badges77 silver badges115 bronze badges

asked Feb 26, 2014 at 5:25

compyutech's user avatar

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 Jawor's user avatar

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.Delete

    I 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

  • 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

1 / 1 / 0

Регистрация: 03.11.2018

Сообщений: 12

1

Word

Удаление страниц в документе

04.11.2018, 16:14. Показов 4835. Ответов 1


Студворк — интернет-сервис помощи студентам

Добрый день!
Проблема следующая:
Есть туча файлов, в которых нужно удалить первые две страницы.
Шарил по просторам и нашел следующие виды макросов
Пакетное форматирование:

Кликните здесь для просмотра всего текста

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
Sub batchFormating()
'массовое форматирование документов, находящихся в одной папке
Dim myFile As String
Dim myDoc As Document
Dim nStart As Long, nEnd As Long
Dim path As String
Dim fDlg As FileDialog
Dim ext() As Variant
Dim i As Long
On Error Resume Next
'msoFileDialogFilePicker – позволяет пользователям выбрать один или более файлов.
'Пути к файлам, выбранным пользователям, сохраняются в коллекции элементов FileDialogSelectedItems
Set fDlg = Application.FileDialog(msoFileDialogFolderPicker)
'Выбираем папку с файлами для форматирования
With fDlg
   .Title = "Выберите папку, содержащую документы и нажмите ДА"
   .AllowMultiSelect = False
   .InitialView = msoFileDialogViewList
   If .Show <> -1 Then
      MsgBox "Отменено", , "Массовое форматирование"
      Exit Sub
   End If
   path = fDlg.SelectedItems.Item(1)
   If Right(path, 1) <> "" Then path = path + ""
End With
'Закрываем любые открытые документы
If Documents.Count > 0 Then
   Documents.Close SaveChanges:=wdPromptToSaveChanges
End If
ext = Array("*.doc", "*.rtf", ".docx") 'Заносим в массив типы расширений
For i = 0 To UBound(ext) 'Запускаем цикл обхода файлов с расширениями из массива
'Заносим в переменную полный путь к первому файлу в папке,
'имена следующих файлов будут получены в цикле функцией Dir$() без аргументов
myFile = Dir$(path & ext(i))
'Запускаем цикл обработки каждого файла в папке
While myFile <> ""
   'Открываем каждый файл без видимости для пользователя
   Set myDoc = Documents.Open(path & myFile, Visible:=False)
   'Изменяем форматирование каждого файла
   With myDoc
      With .Range
         With .PageSetup
            .LeftMargin = CentimetersToPoints(2)
            .RightMargin = CentimetersToPoints(1)
            .TopMargin = CentimetersToPoints(1)
            .BottomMargin = CentimetersToPoints(2)
         End With
         .Paragraphs.FirstLineIndent = CentimetersToPoints(1.25)
         .ParagraphFormat.LineSpacingRule = wdLineSpaceSingle
         With .Font
            .ColorIndex = wdBlack
            .Name = "Times New Roman"
            .Size = 12
         End With
      End With
      .Close SaveChanges:=wdSaveChanges
   End With
   myFile = Dir$()   'получаем следующее имя файла из папки
Wend
Next i
Set fDlg = Nothing
Set myDoc = Nothing
End Sub

И, непосредственно, сам макрос удаления страниц

Кликните здесь для просмотра всего текста

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Sub DeletePagesFromSections()
Dim nStart As Long, nEnd As Long
      With Selection
        'Переход к началу первой страницы
        .GoTo wdGoToPage, wdGoToAbsolute, 1
        'Запоминаем положение
        nStart = .Start
        'Переход к началу девятой страницы
        .GoTo wdGoToPage, wdGoToAbsolute, 3
        'Запоминаем положение
        nEnd = .Start
        'Выделяем
        .SetRange nStart, nEnd
        'Удаляем
        .Delete
      End With
End Sub

Бьюсь над совокуплением оных! Но все равно не получается. Будьте добры, подскажите, как это сделать.



0



If you work with long Microsoft Word documents and frequently have to delete pages, you’ll appreciate this simple VBA procedure.

Image: BigTunaOnline/Shutterstock

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:

  1. Click the Quick Access Toolbar dropdown and choose More Commands.
  2. In the left pane, click Customize Ribbon.
  3. Click the Customize button (Figure A) to create the shortcut.
  4. In the resulting dialog, choose Macros from the Categories list (it’s near the bottom of the list).
  5. From the Save Changes In dropdown, choose the active document.
  6. 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.
  7. 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.Quickly Delete Multiple Pages in Your Word Document

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.

  1. To begin with, put cursor on the page you want to delete.
  2. 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.
  3. Secondly, click “Normal”.
  4. Then click “Insert” and choose “Module” on that menu.Click "Normal"->Click "Insert"->Click "Module"
  5. Open the new module by double click.
  6. 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
  1. Finally, click “Run” button or hit “F5”.Paste Codes->Click "Run"

Delete Multiple Pages

  1. Follow steps above to install and run a macro.
  2. 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
  1. 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.
  2. Then click “OK” to proceed.Enter Page Numbers->Click "OK"

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

Понравилась статья? Поделить с друзьями:
  • Удалить столбец таблицы в текстовом процессоре word вместе с ее содержимым можно выделив строку
  • Удалить стили ячеек excel 2010
  • Удалить стили в excel макрос
  • Удалить ссылку на внешний файл excel
  • Удалить ссылку в таблице excel