如何使用VBA更改图像大小

时间:2017-10-23 10:52:42

标签: vba ms-word

我有这段代码:

Selection.InlineShapes.AddPicture FileName:=path & "\" & "image.png", LinkToFile:=False, SaveWithDocument:=True
Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter

Selection.InlineShapes.Item(1).ScaleHeight = 80
Selection.InlineShapes.Item(1).ScaleWidth = 80

但是出现5941错误消息:

Run-time error '5941' the requested member of the collection does not exist.

我想设置特定的高度和宽度。

我该如何解决?

2 个答案:

答案 0 :(得分:2)

哦(更新的答案)...请尝试这个,(关于文字背后的图片的评论令人困惑......)。现在的问题似乎是当你改变了段落格式化您实际取消选择图像。这可以通过在添加图像之前更改段落对齐来解决。可以这样做:

Sub ap()
    Dim imgPath As String
    imgPath = imgPath & "image.png"

    Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter

    Dim myIlsh As InlineShape
    Set myIlsh = Selection.InlineShapes.AddPicture(FileName:=imgPath, LinkToFile:=False, SaveWithDocument:=True)

    myIlsh.ScaleHeight = 80
    myIlsh.ScaleWidth = 80

    Set myIlsh = Nothing
End Sub

如果你的图像不是与文本内联的,你应该可以用它来修复它们:

Sub resizeImage()
    Dim iLoop As Long
    For iLoop = 1 To ActiveDocument.Shapes.Count
        ActiveDocument.Shapes(iLoop).Select
        If MsgBox("resize shape & convert to inline?", vbYesNo) = vbYes Then

            If ActiveDocument.Shapes(iLoop).WrapFormat.Type <> wdWrapInline Then
                ActiveDocument.Shapes(iLoop).ConvertToInlineShape
            End If
            ActiveDocument.Shapes(iLoop).ScaleHeight 0.8, msoTrue
            ActiveDocument.Shapes(iLoop).ScaleWidth 0.8, msoTrue

        End If
    Next iLoop
End Sub

答案 1 :(得分:1)

您可能需要查看This。 以下是该网站的评论:

  

基础:

     

使用关联形状容器的.ScaleHeight和.ScaleWidth属性调整图片大小。此属性确定相对于原始图片大小的百分比大小,以缩放图像。

     

示例:

     

以下代码将图片高度调整为原始图片高度的90%:

     

InlineShapes.Item(1).ScaleHeight = 90

或者,您可以在创建图像时更改尺寸:

ActiveDocument.Shapes.AddPicture FileName:=path & "\" & "image.png", _
LinkToFile:=False, _
SaveWithDocument:=True, _
Left:=-0, _
Top:=0, _
Anchor:=Selection.Range, _
Width:=50, _
Height:=50