At first, want to say hello beacuse it's my first post here
I am trying to add picture form hard drive into bookmark named "test" in MS Word
In step 1 (no picture in bookmark) picture is adding to proper place.
In step 2 (picture already in bookmark) when running macro once again, picture is adding just next to old one (without replacing it).
I searched throught many threads (also from this forum) in that case but none of these works.
Sub test2()
Dim test As InlineShape
Dim Rng As Range
With ActiveDocument
'Identify current Bookmark range
If .Bookmarks.Exists("test") Then
Set Rng = .Bookmarks("test").Range
With Rng
'Delete existing image (if applicable)
Debug.Print (a)
While .InlineShapes.Count > 0
Debug.Print (b)
.InlineShapes(1).Delete
Debug.Print (b)
Wend
End With
'Place new image
Set test = .InlineShapes.AddPicture(FileName:="C:\images\250V.png", LinkToFile:=False, Range:=Rng)
End If
Debug.Print (C)
'Re-insert the bookmark
.Bookmarks.Add "test", Rng
Debug.Print (d)
End With
End Sub
I tried also that way:
Sub InsertImage3()
Dim PicPath As String
Dim BmkName As String
PicPath = "C:\images\250V.png"
BmkName = "test"
With ActiveDocument
If .Bookmarks.Exists(BmkName) Then
Dim WrdPic As Word.InlineShape
Set WrdPic = .Bookmarks(BmkName).Range _
.InlineShapes.AddPicture(PicPath, False, True)
End If
End With
End Sub
both ways adding pictures next to each other.
I also tried this version
Sub UpdateBookmarkedImage(BmkNm As String, NewTxt As String)
Dim BmkRng As Range
Dim j As Long
With ActiveDocument
If .Bookmarks.Exists(BmkNm) Then
Set BmkRng = .Bookmarks(BmkNm).Range
BmkRng.InlineShapes(1).Delete
BmkRng.InlineShapes.AddPicture FileName:=NewTxt
.Bookmarks.Add BmkNm, BmkRng
End If
End With
Set BmkRng = Nothing
End Sub
Sub UpdateImage()
Dim BmkNm As String
Dim NewTxt As String
BmkNm = "test"
NewTxt = "C:\Users\Laptop\Desktop\wersje\bkt\images\250V.png"
UpdateBookmarkedImage BmkNm, NewTxt
End Sub
but getting error '5941' The requested member of the collection does not exist, when clicking debug this line is highlighted
BmkRng.InlineShapes(1).Delete
just on other note, I there is better way (more 'rigid') to insert pictures - to give them ID's or so?
I heard that indexes of InlineShapes could be hard to manage if on page will be many images which will change. Please let me know.