César Amorim
César Amorim

Reputation: 357

Inserting a image in first page header, and defining its position in VBA

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

Upvotes: 0

Views: 1796

Answers (2)

César Amorim
César Amorim

Reputation: 357

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

Upvotes: 0

Cindy Meister
Cindy Meister

Reputation: 25663

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.

Upvotes: 1

Related Questions