通过VBA更改Word Shape中的图像

时间:2017-11-10 06:04:21

标签: vba ms-word word-vba

我有InlineShape的word文档。我希望通过VBA以编程方式更改此形状的图像。但是我发现的所有例子都取代了旧的形状。并且所有格式(大小,边框等)都将丢失。如何只更改形状中的图像而不会丢失格式。

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()

但不能从旧图片复制格式。如何使代码从旧(已删除)图片中复制所有格式设置?

1 个答案:

答案 0 :(得分:1)

您可以将图像包装在内容控件中 - 保存大小详细信息,删除并替换新图像,然后重新应用大小详细信息。

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