【问题标题】:Change image in Word Shape via VBA通过 VBA 更改 Word Shape 中的图像
【发布时间】:2018-04-23 07:35:05
【问题描述】:

我有包含 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()

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

【问题讨论】:

  • 你的问题不是很清楚......形状中是否有图像 - 它是什么样的形状,类似于文本框?
  • 感谢您的关注,对我糟糕的英语感到抱歉。我的任务是这个。在 Word 文档中的文本块中放置了一张图片。上面的代码(我现在添加)用另一个替换这张图片而不保存格式。我只需要替换图像并保存旧图片的格式。
  • 问题:如果您手动将新图片粘贴到文档中,是否可以在删除旧图片之前使用格式刷将格式从旧图片应用到新图片?如果是这样,那么应该可以通过编程方式实现。
  • 我也尝试过应用复制格式的想法。但在这种情况下,并非所有格式设置都适用于新图像。例如图片和文本换行的大小......是否可以像在 html 标签 或 winform 控件中那样轻松更改图像的形状?

标签: vba ms-word


【解决方案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

【讨论】:

  • 谢谢!你对我帮助很大!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-02
  • 1970-01-01
  • 2016-06-10
  • 1970-01-01
相关资源
最近更新 更多