简体   繁体   English

使用Excel-VBA创建字符串/文本和图像并将其插入到Word文档表单元格中

[英]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 从几天以后,我就尝试使用Excel-VBA创建Word文档

Step by Step: first: create Word-Document and add a Table (Mailing-Label) second: fill sometext into some cells. 循序渐进:首先:创建Word文档并添加表格(Mailing-Label),其次:在某些单元格中填充文本。 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. 如您所料,当您将文本分配给Range ,就像在输入文本一样。 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. 第二行代码,插入图像,就像选择整个单元格(在这种情况下)然后插入图像:它替换了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. 使用Range对象时,也适用相同的原理:需要折叠才能为其添加内容。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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