Vba word удаление страницы

  • 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. Показов 4824. Ответов 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



Look up the definition of IsEmpty in the VBA language reference. It doesn’t do what you imagine.

The correct way to find out if there is textual content is to check the number of characters. In VBA, this is typically done with the function Len (=length). You’d think that it the comparision should be to 0 (zero), but that’s not the case for a paragraph, because a Word paragraph always contains it’s paragraph mark (ANSI 13).

Also, no need to select the paragraph or range in order to delete it, just use the Deletemethod directly on the par.Range. (Which means you also don’t need to pass a Word.Application object.

Also note that your code doesn’t do anything to pages, only to paragraphs… It could deleted empty pages, depending on how things are formatted, but it might be wise to rename the Function and comment how it’s supposed to work.

So more like this:

Public Function DeleteBlankPages(wd As Word.Document)  
    Dim par As Paragraph
    For Each par In wd.Paragraphs
        If Len(par.Range.Text) <= 1 Then
            par.Range.Delete
        End If
    Next par       
End Function

Hello everyone, today in this article we will show you how to use VBA to select and delete a single page in Word. Visual Basic for Applications is the language behind Office applications that allows you to automate tasks. But using VBA in Word has its challenges. You also can modify tables in Microsoft Word using VBA

Microsoft Word is a widely used commercial word processing program developed by Microsoft. Microsoft Word is part of the Microsoft Office suite, but can also be purchased as a stand-alone product. And yes, you can even use Microsoft Word for free

Microsoft Word does not provide a quick select option to select and delete pages. Use this VBA procedure to select a specific page and delete it. The article How to use a VBA procedure that deletes the current page in a Word document shows you how to delete the current page in a Word document. This is useful when you are on the page you want to delete. If you need to select the page before deleting it, you’ll need a bit more code.

How to use VBA to select and delete a single page in Word

Delete current page

Step 1 : To start, put cursor on the page you want Remove.

Step 2 : Open vba-editor in Word by clicking the “developertab “and then”visual basic”. If the “Developer” tab is not yet available on the ribbon, press “Alt+ F11” instead.

Step 3 : Second, click “Normal”.

Step 4 : Then click “Insert” and choose “Module” in that menu.

step 5 : Open the new module double click.

Step 6 : Y paste following codes there:

Sub DeleteCurrentPage() Dim objDoc As Document

‘ InitializeSet ​​objDoc = ActiveDocument

‘ Delete current page.objDoc.Bookmarks(“Page”).Range.DeleteEnd Sub

Step 7 : Finally, click on “Run“or press” buttonF5”.

delete multiple pages

Step 1 : Follow the steps above to install on pc and run a macro.

Step 2 : Replace the macro With this:

Sub DeletePagesInDoc() Dim objRange As RangeDim strPage As StringDim objDoc As DocumentDim nSplitItem As Long

Application.ScreenUpdating = False

‘ Initialize and enter the page numbers of the pages to be deleted. Set objDoc = ActiveDocumentstrPage = InputBox(“Enter the page numbers of the pages to be deleted: ” & vbNewLine & _“use commas to separate the numbers”, “Delete pages”, “For example: 1,3”)nSplitItem = UBound(Split(strPage, “,”))

‘ Find specific pages and highlight their content. For nSplitItem = nSplitItem To 0 Step -1With ActiveDocumentSelection.GoTo What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=Split(strPage, “,”)(nSplitItem)Set objRange = .Bookmarks(“Page”).RangeobjRange. DeleteEnd WithNext nSplitItem

Application.ScreenUpdating = TrueEnd Sub

Step 3 : Running a macro will activate an input box. Enter the page number of pages to delete and use eat to separate them. don’t go into a space after the comma.

Step 4 : Then click “okay” to proceed.

Last words

We hope you’ll like our article on how to use VBA to select and delete a single page in Word. VBA allows you to use English-like statements to write instructions to create various applications. VBA is easy to learn and has an easy to use user interface where you just need to drag and drop the interface controls. So if you like our article, please share it with others.

I hope you understand this article, How to use VBA to select and delete a single page in Word.

James Hogan

James Hogan

James Hogan is a senior staff writer at Bollyinside, where he has been covering various topics, including laptops, gaming gear, keyboards, storage, and more. During that period, they evaluated hundreds of laptops and thousands of accessories and built a collection of entirely too many mechanical keyboards for their own use.

Word VBA, Delete Page

Jul 04, 2015 in VBA for Word

In this article I will explain how you can use VBA for Word to delete a page. To be clear, there isn’t a “Page” collection where you could just call the delete or remove method of its members. The way to accomplish this is to manually select all the content in a page and delete it.

The function below receives as input a page number and deletes it:

Public Sub DeletePage(ByVal intPage As Integer)
Dim flag As Boolean
'the line number before moving to the left
Dim intLineBefore As Integer
'the line number after moving to the left
Dim intLineAfter As Integer
'the page number before moving to the left
Dim intPageNumberBefore As Integer
'the page number after moving to the left
Dim intPageNumberAfter As Integer
'the last page number
Dim intLastPage As Integer
'the last line numnber
Dim intLastLine As Integer

Selection.EndKey unit:=wdStory
intLastPage = Selection.Range.Information(wdActiveEndPageNumber)
intLastLine = Selection.Range.Information(wdFirstCharacterLineNumber)
'moves the cursor to the start of the document
Selection.HomeKey unit:=wdStory
'gets the currrent page number
If Selection.Range.Information(wdActiveEndPageNumber) _
<> intPage Then
    flag = True
    'keeps going until the page number is found
    While flag = True
        Selection.EndKey unit:=wdLine
        intPageNumberBefore = _
        Selection.Range.Information(wdActiveEndPageNumber)
        intLineBefore = _
        Selection.Range.Information(wdFirstCharacterLineNumber)
        Selection.MoveLeft unit:=wdCharacter, Count:=1
        intPageNumberAfter = _
        Selection.Range.Information(wdActiveEndPageNumber)
        intLineAfter = _
        Selection.Range.Information(wdFirstCharacterLineNumber)
        Selection.MoveRight unit:=wdCharacter, Count:=1
        If intLineAfter = intLineBefore And _
        intPageNumberBefore = intPageNumberAfter Then
           Selection.MoveRight unit:=wdCharacter, Count:=1
        End If
        'checks if page number has been reached
        If Selection.Range.Information(wdActiveEndPageNumber) _
        = intPage Then
           flag = False
        End If
    Wend
End If
'move to the start of the page
Selection.HomeKey
flag = True
'keep selecting until the end of the page
While flag = True
    Selection.EndKey unit:=wdLine, Extend:=wdExtend
    intPageNumberBefore = _
    Selection.Range.Information(wdActiveEndPageNumber)
    intLineBefore = _
    Selection.Range.Information(wdFirstCharacterLineNumber)
    Selection.MoveLeft unit:=wdCharacter, Count:=1, _
    Extend:=wdExtend
    intPageNumberAfter = _
    Selection.Range.Information(wdActiveEndPageNumber)
    intLineAfter = _
    Selection.Range.Information(wdFirstCharacterLineNumber)
    Selection.MoveRight unit:=wdCharacter, Count:=1, _
    Extend:=wdExtend
    If intLineAfter = intLineBefore And intPageNumberBefore _
    = intPageNumberAfter Then
        Selection.MoveRight unit:=wdCharacter, Count:=1, _
        Extend:=wdExtend
    End If
    'if the end of the page is reached delete
    If (Selection.Range.Information(wdActiveEndPageNumber) _
    <> intPage) Then
        Selection.HomeKey unit:=wdLine, Extend:=wdExtend
        Selection.MoveLeft unit:=wdCharacter, Extend:=wdExtend
        Selection.Delete
        flag = False
    ElseIf (Selection.Range.Information(wdActiveEndPageNumber) _
    = intLastPage) Then
        Selection.EndKey unit:=wdStory, Extend:=wdExtend
        Selection.Delete
        flag = False
    End If
Wend
End Sub

Assume we call the function with the parameter 2:

Sub main()
Call DeletePage(2)
End Sub

The second page will be selected by the function:

Word VBA Select Pages
And deleted:

Word VBA, Deleted Page


Code Description:

The first while loop, moves the cursor down line by line until the target page is reached:

While flag = True
    Selection.EndKey unit:=wdLine
    intPageNumberBefore = _
    Selection.Range.Information(wdActiveEndPageNumber)
    intLineBefore = _
    Selection.Range.Information(wdFirstCharacterLineNumber)
    Selection.MoveLeft unit:=wdCharacter, Count:=1
    intPageNumberAfter = _
    Selection.Range.Information(wdActiveEndPageNumber)
    intLineAfter = _
    Selection.Range.Information(wdFirstCharacterLineNumber)
    Selection.MoveRight unit:=wdCharacter, Count:=1
    If intLineAfter = intLineBefore And _
    intPageNumberBefore = intPageNumberAfter Then
        Selection.MoveRight unit:=wdCharacter, Count:=1
    End If
    'checks if page number has been reached
    If Selection.Range.Information(wdActiveEndPageNumber) _
    = intPage Then
        flag = False
    End If
Wend

You might be wondering why I used the Selection.EndKey instead of the Selection.MoveDown function? The object of the first while loop is to loop through all the lines of the document, page by page. If the user scrolls out and we use the Selection.MoveDown function the cursor will skip pages and move directly down:

MoveDown Function Word VBA

Once the target page number has been found the second while loop selects all the lines in the page. Once the end of the page is reached it deletes the content.

  •  Delete Page.docm

If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website  www.software-solutions-online.com

Like this post? Please share to your friends:
  • Vba word текущая папка
  • Vba word текстовые функции
  • Vba word текст по центру
  • Vba word текст закладки
  • Vba word текст в ячейке таблицы