BradSlattery
BradSlattery

Reputation: 115

Attempting to insert an image after the text within a Word table using VBA

I have a table in Word which contains some text within each cell. I would like to insert an image from a file within a cell at the end of the text. At the moment, I only know how to insert an image before the text.

The image below shows a basic table with some text in the first cell: Text in cell

I then run a basic macro to insert a specific image from file into that first cell:

Sub InsertImageIntoCell()
    ActiveDocument.Tables(1).Rows(1).Cells(1).Range.InlineShapes.AddPicture _
    FileName:="C:\Data\tree.png", linktofile:=False, savewithdocument:=True
End Sub

After the macro has run, I end up with an image appearing to the left of the text: Image in cell

Could anyone please provide some insight into how I could have the image insert to the right of the pre-existing text?

Upvotes: 0

Views: 1693

Answers (2)

macropod
macropod

Reputation: 13490

Simpler:

Sub InsertImageIntoCell()
With ActiveDocument
  .InlineShapes.AddPicture FileName:="C:\Data\tree.png", LinkToFile:=False, _
    SaveWithDocument:=True, Range:=.Tables(1).Cell(1, 1).Range.Characters.Last
End With
End Sub

Upvotes: 2

BradSlattery
BradSlattery

Reputation: 115

After Timothy's comment, I managed to do some research and came up with a solution.

Here is my VBA code:

Sub InsertImageIntoCell()
    With ActiveDocument
        Set myRange = .Tables(1).Rows(1).Cells(1).Range
        myRange.Start = myRange.End - 1
        
        .Tables(1).Rows(1).Cells(1).Range.InlineShapes.AddPicture _
        FileName:="C:\Data\tree.png", linktofile:=False, _
        savewithdocument:=True, Range:=myRange
    End With
End Sub

It certainly may not be the best solution, however it works great for me. i.e. it now inserts the image after the text in the cell.

here is the Table before running the macro: Cell before running the macro

And here it is again, after running the macro: Cell after running the macro

Upvotes: 1

Related Questions