简体   繁体   中英

VBA Word Add selected inline shape to a table cell

I have an inline shape object selected in Word and am trying to paste it (move it) into a table cell using VBA. But I can't find any API to do the job. I would like to do this

// C#
myCell.InlineShapes.Add(selection.InlineShapes[1]);

But there are no APIs in VBA or C# that I can find to do that.

I found this SO link that almost does the job , but it loads a picture directly from a file into the table cell.

How can I get the selected image into the cell (either in Shapes or InlineShapes)? Thank you

UPDATE:

I found another example by Cindy Meister here to give me a hint on the right approach. Thank you, Cindy!!

This code finally worked. I had to go through the clipboard and get the cell range to pull in the picture from the clipboard using PasteSpecial. Weird. But it worked. Maybe there is a better way.

// C#
sel.CopyAsPicture();
var cell = table.Cell(row, 1);

// Must use cell.PasteSpecial to pull in the image from the clipboard
var range = cell.Range;
range.PasteSpecial(null, null, WdOLEPlacement.wdInLine, false,
    WdPasteDataType.wdPasteShape);

Try this code:

Sub MoveShapeToTable()
    Dim ish As InlineShape, tblNew As Table
    
    On Error Resume Next
    Set ish = Selection.InlineShapes(1)
    If Err.Number <> 0 Then
        MsgBox "No InlineShapes selected", vbCritical
        Exit Sub
    End If
    On Error GoTo 0
    
    ish.Range.Cut
    With ActiveDocument
        Set tblNew = .Tables.Add(Range:=.Range.Characters.Last, NumRows:=2, NumColumns:=1, _
                     DefaultTableBehavior:=wdWord9TableBehavior)
        tblNew.Cell(1, 1).Range.Paste
    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