Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the image size

Tags:

ms-word

vba

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?

like image 728
Iratzar Carrasson Bores Avatar asked Mar 12 '26 06:03

Iratzar Carrasson Bores


1 Answers

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
like image 118
SlowLearner Avatar answered Mar 15 '26 03:03

SlowLearner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!