Держите верхний / нижний колонтитул в коде VBA для разделения документа - PullRequest
0 голосов
/ 16 октября 2018

Я нашел этот код в сети, который делает именно то, что я ожидал, однако я ищу способ сохранить верхний и нижний колонтитулы.Прямо сейчас он занимает только небольшой основной корпус и удаляет верхний и нижний колонтитулы при копировании в новый документ.Причина, по которой я не делаю это вручную, состоит в том, что существует более 200 страниц.Просматривая код, который я понял, он может иметь какое-то отношение к расширению читаемого диапазона.

Sub SplitIntoPages()
Dim docMultiple As Document
Dim docSingle As Document
Dim rngPage As Range
Dim iCurrentPage As Integer
Dim iPageCount As Integer
Dim strNewFileName As String
Application.ScreenUpdating = False 'Makes the code run faster and reduces screen _
flicker a bit.
Set docMultiple = ActiveDocument 'Work on the active document _
(the one currently containing the Selection)
Set rngPage = docMultiple.Range 'instantiate the range object
iCurrentPage = 1
'get the document's page count
iPageCount = docMultiple.Content.ComputeStatistics(wdStatisticPages)
Do Until iCurrentPage > iPageCount
If iCurrentPage = iPageCount Then
rngPage.End = ActiveDocument.Range.End 'last page (there won't be a next page)
Else
'Find the beginning of the next page
'Must use the Selection object. The Range.Goto method will not work on a page
Selection.GoTo wdGoToPage, wdGoToAbsolute, iCurrentPage + 1
'Set the end of the range to the point between the pages
rngPage.End = Selection.Start
End If
rngPage.Copy 'copy the page into the Windows clipboard
Set docSingle = Documents.Add 'create a new document
docSingle.Range.Paste 'paste the clipboard contents to the new document
'remove any manual page break to prevent a second blank
docSingle.Range.Find.Execute Findtext:="^m", ReplaceWith:=""
'build a new sequentially-numbered file name based on the original multi-paged file name and path
strNewFileName = Replace(docMultiple.FullName, ".doc", "_" & Right$("000" & iCurrentPage, 4) & ".doc")
docSingle.SaveAs strNewFileName 'save the new single-paged document
iCurrentPage = iCurrentPage + 1 'move to the next page
docSingle.Close 'close the new document
rngPage.Collapse wdCollapseEnd 'go to the next page
Loop 'go to the top of the do loop
Application.ScreenUpdating = True 'restore the screen updating
'Destroy the objects.
Set docMultiple = Nothing
Set docSingle = Nothing
Set rngPage = Nothing
End Sub

Что у меня есть: Согласованный верхний / нижний колонтитул, с переменным основным телом.

ЧтоЯ ожидаю: VBA выполняет и разбивает каждую страницу на новый документ.

Что происходит: VBA разбивает каждое основное тело на новый документ и подбрасывает верхний / нижний колонтитулы.

1 Ответ

0 голосов
/ 16 октября 2018

Верхний / нижний колонтитулы документа принадлежат section break, а не отдельным страницам.Таким образом, копирование содержимого страницы не может / не будет включать верхний / нижний колонтитулы.

Один из подходов состоит в том, чтобы

  • получить счетчик страниц
  • настроить цикл на основеколичество страниц
  • удалить все содержимое, кроме страницы, которая должна быть сохранена
  • сохранить файл, закрыть его, повторно открыть файл и повторить удаление для следующегоpage

Другая возможность также заключается в дублировании верхнего / нижнего колонтитула в новом документе.Я изменил ваш код (и отформатировал его!) С помощью нескольких строк, которые делают это.Я предполагаю, что в исходном документе есть только «первичные» верхние и нижние колонтитулы - ни первой, ни даже страницы.

    'get the header
    docSingle.Sections(1).Headers(wdHeaderFooterPrimary).Range.FormattedText = _
        rngPage.Sections(1).Headers(wdHeaderFooterPrimary).Range.FormattedText
    'get the footer
    docSingle.Sections(1).Footers(wdHeaderFooterPrimary).Range.FormattedText = _
        rngPage.Sections(1).Footers(wdHeaderFooterPrimary).Range.FormattedText

Вместо копирования / вставки этот код использует свойство Range.FormattedTextпередать данные.Как правило, лучше избегать буфера обмена и переходить напрямую, хотя могут быть исключения из правила ... Если в исходном документе несколько разделов, этот код должен выбрать верхний / нижний колонтитул раздела для копируемой страницы,именно поэтому он использует rngPage вместо docMultiple для источника.

Sub SplitIntoPages()
    Dim docMultiple As Document
    Dim docSingle As Document
    Dim rngPage As Range
    Dim iCurrentPage As Integer
    Dim iPageCount As Integer
    Dim strNewFileName As String

    Application.ScreenUpdating = False 'Makes the code run faster and reduces screen _
    flicker a bit.
    Set docMultiple = ActiveDocument 'Work on the active document _
    (the one currently containing the Selection)
    Set rngPage = docMultiple.content 'instantiate the range object
    iCurrentPage = 1

    'get the document's page count
    iPageCount = docMultiple.content.ComputeStatistics(wdStatisticPages)
    Do Until iCurrentPage > iPageCount
        If iCurrentPage = iPageCount Then
            rngPage.End = ActiveDocument.Range.End 'last page (there won't be a next page)
        Else
            'Find the beginning of the next page
            'Must use the Selection object. The Range.Goto method will not work on a page
            Selection.GoTo wdGoToPage, wdGoToAbsolute, iCurrentPage + 1
            'Set the end of the range to the point between the pages
            rngPage.End = Selection.Start
        End If
        'rngPage.Copy 'copy the page into the Windows clipboard

        Set docSingle = Documents.Add 'create a new document
        docSingle.content.FormattedText = rngPage.FormattedText 'carry over the page to the new document
        'remove any manual page break to prevent a second blank
        docSingle.Range.Find.Execute findText:="^m", ReplaceWith:=""
        'get the header
        docSingle.Sections(1).Headers(wdHeaderFooterPrimary).Range.FormattedText = _
            rngPage.Sections(1).Headers(wdHeaderFooterPrimary).Range.FormattedText
        'get the footer
        docSingle.Sections(1).Footers(wdHeaderFooterPrimary).Range.FormattedText = _
            rngPage.Sections(1).Footers(wdHeaderFooterPrimary).Range.FormattedText

        'build a new sequentially-numbered file name based on the original multi-paged file name and path
        strNewFileName = Replace(docMultiple.FullName, ".doc", "_" & Right$("000" & iCurrentPage, 4) & ".doc")
        docSingle.SaveAs strNewFileName 'save the new single-paged document

        iCurrentPage = iCurrentPage + 1 'move to the next page
        docSingle.Close 'close the new document
        Set docSingle = Nothing 'release for the next iteration
        Set rngPage = Nothing
        rngPage.Collapse wdCollapseEnd 'go to the next page
    Loop 'go to the top of the do loop
    Application.ScreenUpdating = True 'restore the screen updating
    'Destroy the objects.
    Set docMultiple = Nothing
End Sub
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...