Este artigo mostra como para um utomate Microsoft Word para definir e obter texto do cabeçalho e rodapé em várias secções de um documento.
O cliente de automatização de exemplo primeiro demonstra como criar secções de um documento. Em seguida, o exemplo demonstra como adicionar texto do cabeçalho e rodapé para essas secções. O documento que cria o código de exemplo consiste em três secções:
- A primeira secção contiver duas páginas. Nesta secção, a primeira página cabeçalho e rodapé são diferentes da segunda página.
- A segunda secção contém três páginas. Nesta secção, o cabeçalho da primeira página e o rodapé são diferentes das outras duas páginas.
- A terceira secção contém duas páginas. Nesta secção, todas as páginas partilham o mesmo cabeçalho e rodapé.
Nota : se ou não uma secção contém cabeçalhos ou rodapés diferentes para a primeira página é determinada pela propriedade
DifferentFirstPageHeaderFooter para o objecto de
secção .
O cliente de automatização de exemplo também demonstra como obter as informações de cabeçalho e rodapé de um documento. Depois de abrir um documento, o cliente itera cada página no documento e exporta os cabeçalhos e rodapés para essa página para a janela de depuração. Nota que o código de exemplo contas apenas para
primeira página cabeçalhos/rodapés e
principal cabeçalhos/rodapés; não conta para cabeçalhos/rodapés de
página par .
Exemplo
- Crie um novo projecto EXE padrão no Visual Basic. É criado o Form1 por predefinição.
- No menu projecto , clique em References . Clique das seguintes opções e, em seguida, clique em OK :
- Para o Word 2007, clique em Microsoft Word 12.0 Object Library .
- Para o Word 2003, clique em Microsoft Word 11.0 Object Library .
- Para o Word 2002, clique em Microsoft Word 10.0 Object Library .
- Para o 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 o documento e altere a legenda do Command2 para Obter 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
- Prima a tecla F5 para executar o programa.
- Clique em Criar documento no formulário e repare que o cliente do Visual Basic inicia o Word e cria o novo documento. Quando este processo estiver concluído, o documento está visível. Examinar o documento e repare os vários cabeçalhos e rodapés ao longo do documento.
- Feche o documento novo e, em seguida, saia do Word.
- Clique em Obter cabeçalhos/rodapés no formulário. O cliente do Visual Basic inicia o Word e obtém o texto de cabeçalho/rodapé de cada página no documento. Os resultados aparecem na janela de depuração; comparar estes resultados para o documento.
Para obter informações adicionais sobre código de exemplo adicionais que demonstra a automatização do Microsoft Word a partir do Visual Basic, clique os números de artigo abaixo para visualizar os artigos na base de dados de conhecimento da Microsoft:
220607
(http://support.microsoft.com/kb/220607/EN-US/
)
Como automatizar o Word para efectuar a impressão em série a partir do Visual Basic
261999
(http://support.microsoft.com/kb/261999/EN-US/
)
Como transferir um conjunto de registos ADO para uma tabela do Word com a automatização