0
votes

I'm trying to insert a image in the first page header of a document, trough VBA.

There are multiple lines that can do this, but each has it problem, which I will list:

This is my favorite method, but it inserts the image not in the header of first page, but all the remaining ones, and it also doesn't allow me to set the position:

ActiveDocument.Sections(1).Headers(2).Shapes.AddPicture ("C:\1.jpg")

This returns an out of bounds error:

Set shpCanvas=ActiveDocument.Shapes.AddCanvas(Left:=0, Top:=0, Width:=180, Height:=50)

shpCanvas.CanvasItems.AddPicture FileName:="C:\1.jpg", LinkToFile:=False, SaveWithDocument:=True

Inserts the image directly, but its usually out of position, stays in the middle of the header where I'd rather have it on the left

ActiveDocument.Sections(1).Headers(wdHeaderFooterFirstPage).Range.InlineShapes.AddPicture ("C:\1.jpg")

I'm just a beginner with VBA and word, I apologize for any grotesque ideas I might have

2
One thing you could do to figure out how to do somethig in VBA, is to start recording a macro in Word, manually do whatever you would like to do, stop recording, and look at the code generated in the macro by Word. This often gives good clues.RobertBaron

2 Answers

1
votes

The first code example does work for me - I see the picture on the first page. But since you don't describe how your document is structured I may not be testing what you're using...

You should not try to use a canvas.

The difference between a Shape and an InlineShape is that Word handles the latter like a text character. If the third line is positioning the picture in the middle of the line that paragraph is probably formatted as "centered", rather than "left". Try changing the paragraph formatting.

To position the result when using a Shape an object variable is required to be able to handle what has been inserted. For example:

Dim shp As Word.Shape, ils As Word.InlineShape

Set shp = ActiveDocument.Sections(1).Headers(2).Shapes.AddPicture("C:\1.jpg")
shp.Top = 0
shp.Left = 0

An object is declared, then the picture being inserted is assigned to the object, in one step. Subsequently, the object variable can be used to address the picture.

0
votes

Thanks for your help, more correctly it worked like this

Dim shp2 As Word.Shape
Dim shp3 As Word.InlineShape

Set shp3 = ActiveDocument.Sections(1).Headers(wdHeaderFooterFirstPage).Range.InlineShapes.AddPicture("C:\1.jpg")
                            Set shp2 = shp3.ConvertToShape
                            shp2.Top = 0
                            shp2.Left = 0