简体   繁体   中英

Use Excel-VBA to create and Insert String/Text AND Image to Word Document table-cell

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM