Link to home
Start Free TrialLog in
Avatar of Andreas Hermle
Andreas HermleFlag for Germany

asked on

Insert a new row at the top of each table using VBA

Dear Experts:

I would like to run a macro that performs the following actions:

Insert a new row into all tables of the current document
Insert a graphic into the second cell of this newly added 'header' row
The graphic is located in: C:\MyPictures\MyGraphic.png

Help is much appreciated.

Thank you very much in advance.

Regards, Andreas
SOLUTION
Avatar of Rgonzo1971
Rgonzo1971

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi Andreas, I think this will do it
Sub AddRow()
    Dim tbl As Table
   
    For Each tbl In ActiveDocument.Tables
        tbl.Rows.Add tbl.Rows.First
        tbl.Cell(1, 2).Range.InlineShapes.AddPicture "C:\MyPictures\MyGraphic.png", False, True
    Next
End Sub
Oops, should have refreshed before posting.
Avatar of Andreas Hermle

ASKER

ok, great both codes work just fine. Thank you very much for it, great job.

Graham's code is a more 'elegant' since it does not use selection.

There is one more thing I would like to get added to this code.

The inserted graphic should get its aspect ratio locked and then resized to 4 cm

Help is much appreciated. Thank you very much in advance.

Regards, Andreas
Okay, I got the resizing done on Rgonzo codes, but I can't get it done on Graham's code.


Sub MacroInsertPictureResize()

Dim sFileName As String
Dim ilImage As InlineShape

sFileName = "C:\MyPictures\MyGraphic.jpg"
For Each tbl In ActiveDocument.Tables
    tbl.Rows(1).Select
    Selection.InsertRowsAbove 1
    tbl.Cell(1, 1).Select
    Selection.MoveRight Unit:=wdCell, Count:=1
    Set ilImage = Selection.InlineShapes.AddPicture(sFileName, False, True)
    With ilImage
    .LockAspectRatio = msoTrue
    .Width = CentimetersToPoints(4)
    End With
Next
End Sub
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Since both codes work I think it is fair to award points to both of you.

Thank you very, very much for your swift and professional support. I really appreciate it.

Regards, Andreas