Верхний / нижний колонтитулы документа принадлежат 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