0
votes

I tried since more days to create a Word Document with Excel-VBA

Step by Step: first: create Word-Document and add a Table (Mailing-Label) second: fill sometext into some cells. Works great!

Now my Problem: at last, i want to append an Picture in the cell. My Problem is, the Image RANGE clear the old text. And i don't know, how to set the Image and the text at the end of the Loop.

My code

oDoc.Tables(1).Cell(zeile, spalte).Range.Text = "some string"
oDoc.Tables(1).Cell(zeile, spalte).Range.InlineShapes.AddPicture path_to_image
2
Has a contribution helped you solve the issue?Cindy Meister

2 Answers

1
votes

The way to understand what's happening is to think about how this would work if you were doing this manually, working with a selection. When you assign text to a Range that's like typing it in, as you'd expect. The second line of code, inserting the image, is like selecting the entire cell (in this case) then inserting the image: it replaces what's in the Range. When working manually, if you had selected the entire cell, you'd press Right Arrow or click at the end to put the focus after what had been typed.

The same principle applies when using a Range object: it needs to collapse in order to add something to it.

The following code example demonstrates this. It also highlights how the code can be made more efficient by assigning the table and the target range to objects.

Dim tbl As Word.Table 'or As Object if using late-binding
Dim rng As Word.Range 'or As Object if using late-binding
Dim chrCount As Long

Set tbl = oDoc.Tables(1)
Set rng = tbl.Cell(zeile, spalte).Range
rng.Text = "test"
chrCount = rng.Characters.Count
'Get the end of the cell content
Set rng = rng.Characters(chrCount - 1)
rng.Collapse wdCollapseEnd
rng.InlineShapes.AddPicture path_to_image
0
votes

May be something like

Sub Test()
Dim Wrd As Word.Application
Dim oDoc As Word.Document

Set Wrd = CreateObject("Word.Application")
Wrd.Visible = True
Set oDoc = Wrd.Documents.Add
oDoc.Tables.Add oDoc.Range, 3, 3

zeile = 2
spalte = 2
path_to_image = "C:\Users\user\Desktop\Pull2.jpg"

oDoc.Tables(1).Cell(zeile, spalte).Range.Select

    With Wrd.Selection
    .TypeText Text:="some string"
    .InlineShapes.AddPicture path_to_image
    End With

End Sub