Copy/Paste Header from Template

时间:2017-12-18 07:51:34

标签: word-vba

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:

$username = $this->input->post('username');

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?

2 个答案:

答案 0 :(得分:2)

感谢Kazimierz Jawor,我得到了代码。这是更新的代码:

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

答案 1 :(得分:2)

使用以下对象:

  • Word Sections (index_number) ,或

  • Excel' Series (index_number)

... index_number (恼人地)并不总是代表对象"位置编号"或位置,但我们可以确认这样的子在哪里:

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

...或文本函数可用于查找具有特定文本(或其他属性)的对象的 index_number

相关问题