我需要創建一個 Word-Template,它動態地將徽標添加到字母的標題中。為了簡化用戶體驗,原始模板只生成一頁。這個程序是這樣的:
- 用戶通過 Word 中的“檔案>新建”打開模板
- 用戶可以通過用戶表單在不同的公司和徽標之間進行選擇
- 根據公司/標志的選擇,在信中添加不同的內容
我確實有一個限制,即第一頁上的頁腳與第二頁之后的頁腳不同。
這意味著,當我通過 VBA 代碼將圖片添加到第一頁的標題中并添加文本(或僅添加空格)時,徽標不會重復。
所以基本上我的問題是,如果我可以從第二頁開始將圖片添加到標題中,而該頁面尚不存在?
我目前的代碼類似于以下內容,盡管我已經洗掉了影像格式的部分,因為我認為它不相關:
With ActiveDocument
.Sections(1).Footers(wdHeaderFooterFirstPage) _
.Range.InlineShapes.AddPicture(path)
End With
我也試過搶先將頁眉添加到以下頁面,但似乎不起作用
With ActiveDocument
.Sections(1).Footers(wdHeaderFooterFirstPage) _
.Range.InlineShapes.AddPicture(path)
End With
With ActiveDocument
.Sections(1).Footers(wdHeaderFooterPrimary) _
.Range.InlineShapes.AddPicture(path)
End With
uj5u.com熱心網友回復:
我已經包含了兩個陳述句來放置圖片。要么會作業:
Sub AddGraphicPage2()
Application.ScreenUpdating = False
Dim aSection As Section
For Each aSection In ActiveDocument.Sections
With aSection
.Headers(wdHeaderFooterPrimary).Shapes.AddPicture FileName:="C:\picture.png"
.Headers(wdHeaderFooterPrimary).Range.InlineShapes.AddPicture FileName:="C:\picture.png"
End With
Next aSection
Application.ScreenUpdating = True
End Sub
檢查所有部分使其成為通用宏,它也可以處理比單個頁面更復雜的檔案。
uj5u.com熱心網友回復:
當我添加第二(和第三等)頁面時,我想出了為什么影像“移動”到第 2 頁。這與我添加影像的方式有關。
最初我將錨點定義為Anchor:=Selection.Range. 我只是使用代碼,我知道它可以處理影像的格式。
所以我剛剛洗掉了錨點,現在影像在每個標題中都正確附加,無論是在第 1 頁、第 2 頁還是第 13 頁。
見下文,對我有用的代碼。
當然,我確實在需要時呼叫的函式中正確實作了它;-)
ActiveDocument.Sections(1).PageSetup.DifferentFirstPageHeaderFooter = True
' Insert image in header for page 1
With ActiveDocument.Sections(1).Headers(wdHeaderFooterFirstPage)
With .Shapes.AddPicture(FileName:=filename, LinkToFile:=False, SaveWithDocument:=True)
.name = "Logo_Page1"
.Width = CentimetersToPoints(21)
.Height = CentimetersToPoints(3)
.RelativeHorizontalPosition = wdRelativeHorizontalPositionPage
.Left = CentimetersToPoints(0)
.RelativeVerticalPosition = wdRelativeVerticalPositionPage
.Top = CentimetersToPoints(0)
.WrapFormat.Type = wdWrapBehind
End With
End With
' Insert image in header from page 2 onwards
With ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary)
With .Shapes.AddPicture(FileName:=filename, LinkToFile:=False, SaveWithDocument:=True,Anchor:=Selection.Range)
.name = "Logo_Page2"
.Width = CentimetersToPoints(21)
.Height = CentimetersToPoints(3)
.RelativeHorizontalPosition = wdRelativeHorizontalPositionPage
.Left = CentimetersToPoints(0)
.RelativeVerticalPosition = wdRelativeVerticalPositionPage
.Top = CentimetersToPoints(0)
.WrapFormat.Type = wdWrapBehind
End With
End With
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/380744.html
