Reputation:
I have a template, and it has a page which contains images in the header. I want to copy those images to my ActiveDocument. I am using the following code:
Set doc = ActiveDocument
strTemplate = "C:\Users\rajtilak\Desktop\Report.dotx"
Set docTemplate = Documents.Open(strTemplate)
Set hdr1 = docTemplate.Sections(1).headers(wdHeaderFooterPrimary)
Set hdr2 = doc.Sections(3).headers(wdHeaderFooterPrimary)
hdr1.Range.Copy
hdr2.Range.PasteAndFormat wdFormatOriginalFormatting
docTemplate.Close False
This is working fine, except that it is not copying the header from section 1 but section 5 of the template. Is there any other way to copy the header from a Word file using VBA?
Upvotes: 1
Views: 4672
Reputation: 21619
With objects like:
...the index_number
(annoyingly) isn't always representative of the objects "position number" or location, but we can confirm what's where with a sub like this:
Sub ListHeaders()
Dim s As Integer, sec As Section, secs As Sections, outStr As String
Dim h As Integer, hdr As HeaderFooter, hdrs As HeadersFooters
Set secs = ActiveDocument.Sections
For s = 1 To secs.Count
outStr = outStr & "-----" & _
"Section #" & s & " of " & secs.Count & _
" : " & Replace(secs(s).Range.Text, vbCr, "") & _
"-----" & vbCrLf
Set hdrs = ActiveDocument.Sections(s).Headers
outStr = outStr & " Header 1: wdHeaderFooterPrimary : " & Replace(hdrs(wdHeaderFooterPrimary).Range.Text, vbCr, "") & vbCrLf
outStr = outStr & " Header 2: wdHeaderFooterFirstPage : " & Replace(hdrs(wdHeaderFooterFirstPage).Range.Text, vbCr, "") & vbCrLf
outStr = outStr & " Header 3: wdHeaderFooterEvenPages : " & Replace(hdrs(wdHeaderFooterEvenPages).Range.Text, vbCr, "") & vbCrLf
outStr = outStr & vbCrLf
Next s
MsgBox outStr
End Sub
... or text functions could be used to find the index_number
for an object with specific text (or other attributes).
Upvotes: 1
Reputation:
Thanks to Kazimierz Jawor, I got the code working. Here is the updated code:
Dim docTemplate As Document
Dim strTemplate As String
Dim hdr1 As headerfooter
Dim hdr2 As headerfooter
Dim doc As Document
Set doc = ActiveDocument
strTemplate = "C:\Users\rajtilak\Desktop\Report.dotx"
Set docTemplate = Documents.Open(strTemplate)
Set hdr1 = docTemplate.Sections(1).headers(wdHeaderFooterFirstPage)
Set hdr2 = doc.Sections(3).headers(wdHeaderFooterPrimary)
hdr1.Range.Copy
hdr2.Range.Paste
docTemplate.Close False
Upvotes: 2