簡體   English   中英

使用Excel-VBA創建字符串/文本和圖像並將其插入到Word文檔表單元格中

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

從幾天以后,我就嘗試使用Excel-VBA創建Word文檔

循序漸進:首先:創建Word文檔並添加表格(Mailing-Label),其次:在某些單元格中填充文本。 很棒!

現在我的問題是:最后,我想在單元格中添加圖片。 我的問題是,圖像范圍清除了舊文本。 而且我不知道如何在循環末尾設置圖像和文本。

我的密碼

oDoc.Tables(1).Cell(zeile, spalte).Range.Text = "some string"
oDoc.Tables(1).Cell(zeile, spalte).Range.InlineShapes.AddPicture path_to_image

理解正在發生的事情的方法是考慮如果您通過選擇手動進行此操作,它將如何工作。 如您所料,當您將文本分配給Range ,就像在輸入文本一樣。 第二行代碼,插入圖像,就像選擇整個單元格(在這種情況下)然后插入圖像:它替換了Range中的內容。 當手動工作,如果你已經選擇了整個小區,你會按下右箭頭鍵或在最后單擊放了哪些類型的焦點。

使用Range對象時,也適用相同的原理:需要折疊才能為其添加內容。

下面的代碼示例對此進行了演示。 它還強調了如何通過將表和目標范圍分配給對象來提高代碼效率。

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

可能像

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