2017-12-18 267 views
1

我有一個模板,它有一個包含圖片標題的頁面。我想將這些圖像複製到我的ActiveDocument。我正在使用下面的代碼:從模板複製/粘貼標題

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 

這工作正常,但它不是從模板的第1部分,但第5部分複製標題。有沒有其他方法使用VBA從Word文件中複製標題?

+0

如果將'hdr1'設置爲與[此列表(MSDN)]不同類型的標頭,那麼該怎麼辦?(https://msdn.microsoft.com/zh-cn/vba/word-vba/articles/wdheaderfooterindex-enumeration -字)。 –

+0

它的工作!所以我做的是,我從中複製標題的模板,因爲我從中複製的頁面,我將代碼更改爲: 設置hdr1 = docTemplate.Sections(1).headers(wdHeaderFooterFirstPage) 其餘的,我將代碼更改爲: 設置hdr2 = doc.Sections(3).headers(wdHeaderFooterPrimary) 它工作。 – rajb

回答

2

感謝卡齊米日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 
2

有了這樣的對象:

...的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