Search code examples
c#ms-wordoffice-interopoffice-addinsword-interop

InlineShape not added to Range after calling AddPicture in Microsoft Word


I'm creating a Microsoft Word 365 Add-in where I need to be able to add and remove inline shapes. I currently have the following test code:

bookmark.Range.InlineShapes.AddPicture("c:\\temp\\test.png");

And although the InlineShape gets added to the page, and seemingly on the correct position, i.e. within the provided bookmark, the bookmark.Range.InlineShapes collection stays empty:

Assert.IsTrue(bookmark.Range.InlineShapes.Count > 0); // This fails

As far as I can see, the shape is actually not added to the range, but directly after it.

This behavior is odd and causes problems in my situation, where I need to be able to iterate the inline shapes of the bookmark later on, especially to be able to remove (toggle) the image again. But without the inline shape as part of the bookmark

What am I doing wrong and how can I fix this, in such way that the inline shape is becoming part of the bookmark again?


Solution

  • That's because your code doesn't insert the shape within the bookmark. This is a quite common misunderstanding. You need to first point a Range object to the bookmark range. Then, add the InlineShape to your Range object's range, then extend the range by one character. Finally, re-apply the bookmark to the Range object's range.

    Following is a VBA example:

    Sub Demo()
    Dim wdRng As Word.Range, BkMkNm As String
    BkMkNm = "MyBookmark"
    With ActiveDocument
      'Confirm that the bookmark exists
      If .Bookmarks.Exists(BkMkNm) Then
        Set wdRng = .Bookmarks(BkMkNm).Range
        'Delete existing contents
        wdRng.Text = vbNullString
        'Insert Pic
        .Range.InlineShapes.AddPicture FileName:="PictureFullName", Range:=wdRng
        'Extend Range
        wdRng.End = wdRng.End + 1
        'Re-apply bookmark
        .Bookmarks.Add BkMkNm, wdRng
      End If
    End With
    End Sub