通过vba将图片添加到Word的标题

时间:2017-11-14 12:09:26

标签: vba ms-access ms-word

我试图通过MS Access VBA将图片插入到word文件的标题中。我似乎无法使代码工作:

Sub Insertpictoheader()
    Dim oHeader As Word.HeaderFooter
    Dim sh As Word.Shape, ils As Word.InlineShape

    Set oSec = ActiveDocument.Sections(1)
    Set oHeader = oSec.Headers(wdHeaderFooterFirstPage)
    oHeader.Range.InlineShapes.AddPicture "C:\Desktop\Logo.png"
End Sub

什么都没有出现,我可以将图像放入文件而不是标题。

1 个答案:

答案 0 :(得分:2)

下面的方法在标题中创建一个表并添加一个图像。只需提供图像的路径。

根据需要修改它以满足您的需求。

Public Sub UpdateHeader(oDoc As Word.Document)
    Dim oSec As Word.Section, rng As Range

    For Each oSec In oDoc.Sections
        Set rng = oSec.Headers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range
            With rng
                .Tables.Add Range:=rng, NumRows:=1, NumColumns:=1, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=wdAutoFitWindow
                With .Tables(1)
                    .Borders.InsideLineStyle = wdLineStyleNone
                    .Borders.OutsideLineStyle = wdLineStyleNone
                    .Rows.SetLeftIndent LeftIndent:=-37, RulerStyle:=wdAdjustNone
                    .Cell(1, 1).Range.InlineShapes.AddPicture filename:="Your file path", LinkToFile:=False, SaveWithDocument:=True
                End With
            End With
    Next oSec
End Sub