Changing the image size

I have this code:

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

But a 5941 error message appear:

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

I want to set specific Height and Width.

How can I fix it?

Upvotes: 3

Views: 19179

Answers (2)

SlowLearner
SlowLearner

Reputation: 3294

Oh (updated answer)... please try this then, (the comment about the image being behind text was confusing...). The problem now seems to be that when you change the paragraph formatting you actually deselect the image. This could be addressed by changing the paragraph alignment BEFORE adding the image. It can be done like this:

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

In case you DO have images that are not inline with text you should be able to fix them with this:

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

Upvotes: 2

Elias Wick
Elias Wick

Reputation: 493

You might want to look at This. Here is a comment from the site:

Basics:

Pictures are resized using the .ScaleHeight and .ScaleWidth property of their associated shape container. This property determines the size in percent relative to the original picture size to scale the image.

Example:

The following code resizes the picture height to 90% of the original picture height:

InlineShapes.Item(1).ScaleHeight = 90

Alternatively you can change the size when creating the image:

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

Upvotes: 2

Related Questions