如何使用来自 excel vba 的后期绑定在 wordDocument.header 中插入图片

How to insert a picture in wordDocument.header using late binding from excel vba

来自EXCEL VBA我想在word文档中插入图片 我可以打开一个word文档 但是在 word 中激活 header 时出现 Object required 错误。 如何设置header为激活的object并在右上角插入图片?


Sub insertPicInWordHeader()
        Dim wdApp As Object
        Dim wdDoc As Object
        Dim rng As Range
        'Turn off error handling since if the Application is not found we'll get an error
        'Use Late Binding and the GetObject method to find any open instances of Word
        On Error Resume Next
        Set wdApp = GetObject(, "Word.Application")
        wdApp.Visible = True

        On Error GoTo 0

        'Check to see if we found an instance.  If not you can create one if you desire
        If wdApp Is Nothing Then
            MsgBox "No open files of Word found"
            Set wdApp = Nothing
            Set wdApp = CreateObject("Word.Application")
            wdApp.Visible = True
        End If

        myFile = "c:\users\bsa\Documents\test.docx"
        Set wdDoc = wdApp.Documents.Open(myFile)
        wdDoc.Activate

        'Check if there are documents in the found instance of Word
        If wdApp.Documents.count > 0 Then



        For Each oSec In wdDoc.Sections
     'This next line gives Error 424 "Object required "
        For Each rng In 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:="c:\users\bsa\Documents\test.png", LinkToFile:=False, SaveWithDocument:=True
                End With
            End With
    Next
    Next
        End If

        'Clean up the Object when Finished
        Set wdApp = Nothing
    End Sub

谢谢@cindymeister 我用这种方式解决了它 post 其他用户

Dim shp As Object
 For Each oSec In wdDoc.sections
         With oSec.Headers(1)
          shp = .InlineShapes.AddPicture(myPath & company & ".png")
           'delete other things in header
           .Range.Delete
           .Range.InlineShapes.AddPicture Filename:=myPath & company & ".png", LinkToFile:=False, SaveWithDocument:=True
           .Range.shp.Height = m_oWord.InchesToPoints(0.72)
           .Range.Paragraphs.Alignment = 2 ' 1 center 2 right
         End With
  Next