Este artigo ilustra como a um utomate do Microsoft Word para definir e recuperar texto de cabeçalho e rodapé em várias seções de um documento.
Primeiro, o cliente de automação de exemplo demonstra como criar seções de um documento. Em seguida, o exemplo demonstra como adicionar texto de cabeçalho e rodapé para essas seções. O documento que cria o código de exemplo consiste em três seções:
- A primeira seção contém duas páginas. Nesta seção, o primeiro cabeçalho de página e rodapé são diferentes da segunda página.
- A segunda seção contém três páginas. Nesta seção, o cabeçalho da primeira página e o rodapé são diferentes das outras duas páginas.
- A terceira seção contém duas páginas. Nesta seção, as páginas de todas as compartilham o mesmo cabeçalho e rodapé.
Observação : se ou não uma seção contém cabeçalhos ou rodapés diferentes para a primeira página é determinada pela propriedade
DifferentFirstPageHeaderFooter para o objeto de
seção .
O cliente de automação de exemplo também demonstra como recuperar as informações de cabeçalho e rodapé de um documento. Depois de abrir um documento, o cliente itera cada página do documento e os cabeçalhos e rodapés para essa página para a janela de depuração de saídas. Observe que o código de exemplo contas apenas para cabeçalhos/rodapés de
página primeira e
principal cabeçalhos/rodapés; ele não dá conta para cabeçalhos/rodapés de
página mesmo .
Exemplo
- Crie um novo projeto Standard EXE no Visual Basic. O Form1 é criado por padrão.
- No menu Project , clique em referências . Clique em uma das seguintes opções e, em seguida, clique em OK :
- Para Word 2007, clique em Microsoft Word 12.0 Object Library .
- Para Word 2003, clique em Microsoft Word 11.0 Object Library .
- Para Word 2002, clique em Microsoft Word 10.0 Object Library .
- Para Word 2000, clique em Microsoft Word 9.0 Object Library .
- Adicione dois botões de comando ao Form1. Alterar a legenda de Command1 para Criar documento e altere a legenda do Command2 para Recuperar cabeçalhos/rodapés .
- Add the following code to Form1:
Option Explicit
Private Sub Command1_Click()
SetHeadersFooters
End Sub
Private Sub Command2_Click()
GetHeadersFooters App.Path & "\mydoc.doc"
End Sub
Sub SetHeadersFooters()
Dim oApp As Word.Application
Dim oSec As Word.Section
Dim oDoc As Word.Document
'Create a new document in Word
Set oApp = New Word.Application
Set oDoc = oApp.Documents.Add
With oDoc
'=== SECTION 1 ==================================================
'Add two pages to the first section where the first page in the
'section has different headers and footers than the second page
Set oSec = .Sections(1)
oSec.PageSetup.DifferentFirstPageHeaderFooter = True
oSec.Range.InsertAfter "Text on Page 1 (Section 1)"
.Range(oSec.Range.End - 1).InsertBreak wdPageBreak
oSec.Range.InsertAfter "Text on Page 2 (Section 1)"
'Add the headers/footers for the first section (that contains two
'pages)
oSec.Headers(wdHeaderFooterFirstPage).Range.Text = _
"Page1 -- Section 1 First Page Header"
oSec.Headers(wdHeaderFooterPrimary).Range.Text = _
"Page2 -- Section 1 Primary Header"
oSec.Footers(wdHeaderFooterFirstPage).Range.Text = _
"Page1 -- Section 1 First Page Footer"
oSec.Footers(wdHeaderFooterPrimary).Range.Text = _
"Page2 -- Section 1 Primary Footer"
'=== SECTION 2 ==================================================
'Add a new section containing three pages where the first page in
'the section has different headers and footers than the other two
'pages
.Range(oSec.Range.End - 1).InsertBreak wdSectionBreakNextPage
Set oSec = .Sections(2)
oSec.PageSetup.DifferentFirstPageHeaderFooter = True
oSec.Range.InsertAfter "Text on Page 3 (Section 2)"
.Range(oSec.Range.End - 1).InsertBreak wdPageBreak
oSec.Range.InsertAfter "Text on Page 4 (Section 2)"
.Range(oSec.Range.End - 1).InsertBreak wdPageBreak
oSec.Range.InsertAfter "Text on Page 5 (Section 2)"
'Add the headers/footers for the second section (that contains
'three pages) -- notice that the second and third pages in this
'section will contain the primary header/footer
oSec.Headers(wdHeaderFooterFirstPage).LinkToPrevious = False
oSec.Headers(wdHeaderFooterFirstPage).Range.Text = _
"Page3 -- Section 2 First Page Header"
oSec.Headers(wdHeaderFooterPrimary).LinkToPrevious = False
oSec.Headers(wdHeaderFooterPrimary).Range.Text = _
"Page4and5 -- Section 2 Primary Header"
oSec.Footers(wdHeaderFooterFirstPage).LinkToPrevious = False
oSec.Footers(wdHeaderFooterFirstPage).Range.Text = _
"Page3 -- Section 2 First Page Footer"
oSec.Footers(wdHeaderFooterPrimary).LinkToPrevious = False
oSec.Footers(wdHeaderFooterPrimary).Range.Text = _
"Page4and5 -- Section 2 Primary Footer"
'=== SECTION 3 ==================================================
'Add a new section containing two pages that all have the same
'header/footer
.Range(oSec.Range.End - 1).InsertBreak wdSectionBreakNextPage
Set oSec = .Sections(3)
oSec.PageSetup.DifferentFirstPageHeaderFooter = False
oSec.Range.InsertAfter "Text on Page 6 (Section 3)"
.Range(oSec.Range.End - 1).InsertBreak wdPageBreak
oSec.Range.InsertAfter "Text on Page 7 (Section 3)"
'Add the headers/footers for the third section (that contains
' two pages)
oSec.Headers(wdHeaderFooterPrimary).LinkToPrevious = False
oSec.Headers(wdHeaderFooterPrimary).Range.Text = _
"Page6and7 -- Section 3 Primary Header Only"
oSec.Footers(wdHeaderFooterPrimary).LinkToPrevious = False
oSec.Footers(wdHeaderFooterPrimary).Range.Text = _
"Page6and7 -- Section 3 Primary Footer Only"
'Save the document
.SaveAs App.Path & "\mydoc.doc"
End With
'Make Word visible to examine the document
oApp.Visible = True
End Sub
Sub GetHeadersFooters(sFile As String)
Dim oApp As Word.Application
Dim oDoc As Word.Document
Dim oSec As Word.Section
Dim oPageStart As Word.Range
Dim iPage As Integer, iTotalPages As Integer, iSection As Integer
Dim sHeader As String, sFooter As String
'Open the document
Set oApp = New Word.Application
Set oDoc = oApp.Documents.Open(sFile)
iTotalPages = oDoc.ComputeStatistics(wdStatisticPages)
'Retrieve the headers and footers on each page
With oDoc
iSection = 0
For iPage = 1 To iTotalPages
'Go to the page represented by the page number iPage and
'retrieve its section
Set oPageStart = oDoc.GoTo(What:=wdGoToPage, _
Which:=wdGoToAbsolute, Count:=iPage)
Set oSec = oPageStart.Sections(1)
'If this is a different section than the one in the previous
'iteration and it has a first page header/.footer, then
'retrieve the first page header/footer for this section.
'Otherwise, retrieve the primary header/footer for this section
If (iSection < oSec.Index) And _
(oSec.PageSetup.DifferentFirstPageHeaderFooter) Then
sHeader = oSec.Headers(wdHeaderFooterFirstPage).Range.Text
sFooter = oSec.Footers(wdHeaderFooterFirstPage).Range.Text
Else
sHeader = oSec.Headers(wdHeaderFooterPrimary).Range.Text
sFooter = oSec.Footers(wdHeaderFooterPrimary).Range.Text
End If
iSection = oSec.Index
'Display the results in the debug window
Debug.Print "Page " & iPage & ", Section " & iSection & _
":" & vbCrLf
Debug.Print " Header: " & sHeader
Debug.Print " Footer: " & sFooter
Next
End With
'Make Word visible to compare the document with the results in the
'debug window
oApp.Visible = True
End Sub
- Pressione a tecla F5 para executar o programa.
- Clique em Criar documento no formulário e observe que o cliente do Visual Basic inicia o Word e cria o novo documento. Quando esse processo for concluído, o documento está visível. Examinar o documento e observe os diferentes cabeçalhos e rodapés em todo o documento.
- Feche o novo documento e saia do Word.
- Clique em Recuperar cabeçalhos/rodapés do formulário. O cliente do Visual Basic inicia o Word e recupera o texto de cabeçalho/rodapé para cada página do documento. Os resultados aparecem na janela de depuração; comparar esses resultados para o documento.
Para obter informações adicionais sobre o código de exemplo adicionais que demonstra a automação do Microsoft Word a partir do Visual Basic, clique nos números abaixo para ler os artigos na Base de dados de Conhecimento da Microsoft:
220607
(http://support.microsoft.com/kb/220607/EN-US/
)
Como automatizar o Word para executar a mala direta a partir do Visual Basic
261999
(http://support.microsoft.com/kb/261999/EN-US/
)
Como transferir um conjunto de registros ADO para uma tabela do Word com a automação