Reputation: 115
I have word document with InlineShape in it. I want programmatically via VBA change image in this shape. But all examples which I found replaced old shape for new. And all formatting (size, borders and so on) are lost. How change only image in shape without losing formatting in it.
Dim pic = _m.off.wd.doc.Range(Start:=startRange).InlineShapes(1)
Dim picRange = pic.Range
Dim cImgPath = getPhotoPathFromRow(cR, cTyp)
Dim newPic = _m.off.wd.doc.InlineShapes.AddPicture(cImgPath, False, True, picRange)
pic.Delete()
But not copy formatting from old picture. How make code to copy all format settings from old (deleted) picture?
Upvotes: 1
Views: 9542
Reputation: 3294
You might be able to wrap your image in a Content Control - save size details, delete and replace with the new image, then reapply the size details.
Sub replaceImage()
Dim originalImage As InlineShape
Dim newImage As InlineShape
Set originalImage = ActiveDocument.InlineShapes(1)
Dim imageControl As ContentControl
If originalImage.Range.ParentContentControl Is Nothing Then
Set imageControl = ActiveDocument.ContentControls.Add(wdContentControlPicture, originalImage.Range)
Else
Set imageControl = originalImage.Range.ParentContentControl
End If
Dim imageW As Long
Dim imageH As Long
imageW = originalImage.Width
imageH = originalImage.Height
originalImage.Delete
Dim imagePath As String
imagePath = "C:\Users\SlowLearner\Pictures\Temp\testImage.jpg"
ActiveDocument.InlineShapes.AddPicture imagePath, False, True, imageControl.Range
With imageControl.Range.InlineShapes(1)
.Height = imageH
.Width = imageW
End With
End Sub
Upvotes: 4