将带有照片的标题插入表格单元格的正确方法?

时间:2019-06-04 22:30:49

标签: vba ms-word

我用VBA创建了一个表,一个3x2的表,在每个单元格中都可以插入图像,但是我不能使用cell.range.insertcaption ..来插入标题。不知道为什么。有正确的解决方案吗?

试图将文件夹中的图片插入通过VBA创建的表格单元中,并添加通过数组迭代的标题。

1 个答案:

答案 0 :(得分:2)

实现它的一个示例(已测试)

Sub test()
Dim Tbl As Table
Set Tbl = ActiveDocument.Tables(1)
Tbl.Cell(2, 2).Range.InlineShapes.AddPicture "C:\users\user\desktop\Flower1.jpg"
Tbl.Cell(2, 2).Range.InlineShapes(1).Select
Selection.InsertCaption Label:="Figure", Title:=" : Caption Flower 1", Position:=wdCaptionPositionBelow
End Sub

编辑:要遍历表单元格,可以尝试类似

Sub test()
Dim Tbl As Table, Cel As Cell, FnameArr As Variant, TitleArr As Variant
Dim Path As String, PicNo As Integer, Rw As Integer, Cl As Integer
Path = "C:\users\user\desktop\"

'array length should cover all the cells in the table
'Use file name of your choice, only two file name used for test
FnameArr = Array("Flower1.jpg", "Flower2.jpg", "Flower1.jpg", "Flower2.jpg", "Flower1.jpg", "Flower2.jpg")
TitleArr = Array("Caption R1C1", "Caption R1C2", "Caption R1C3", "Caption R2C1", "Caption R2C2", "Caption R2C3")

Set Tbl = ActiveDocument.Tables(1)
PicNo = 0

    For Rw = 1 To Tbl.Rows.Count
    For Cl = 1 To Tbl.Rows(Rw).Cells.Count
        If PicNo <= UBound(TitleArr) Then
        Tbl.Cell(Rw, Cl).Range.InlineShapes.AddPicture Path & FnameArr(PicNo)
        Tbl.Cell(Rw, Cl).Range.InlineShapes(1).Select
        Selection.InsertCaption Label:="Figure", Title:=": " & TitleArr(PicNo), Position:=wdCaptionPositionBelow
        Else
        Tbl.Cell(Rw, Cl).Range.Text = "No file name Provided"""
        End If
    PicNo = PicNo + 1
    Next Cl
    Next Rw

End Sub

enter image description here