How to position image in a cell range Excell Macro (vba)

Viewed 40

I am pretty new to coding and I encountered a small Issue. I am trying to make a macro in Excel VBA that will help me move a specific Image within a certain cell range.

After I download it and add it up to my specified Excel sheet the image looks like this:

https://imgur.com/GteP0pM

I would like to have the image resized to fit within a range like:

Set r = ws.Range("C17:O34")

And look something like this: https://imgur.com/rddltWk

The image can be a bit resized manually if need, but I need to have it within that cell range.

So far I tried to have the image selected

Sub selectImage12()
    Worksheets("T-tilbud").Shapes.Range(Array("Picture 12")).Select
End Sub

And then trying to move it to the specified cells, I tried with:

Set r = ws.Range by following this example:

Dim r As Range
Dim ws As Worksheet

Dim imagePath As String
Dim img As Picture

Set ws = Worksheets("CheckListIndustrialisation")
Set r = ws.Range("A1:D4")
imagePath = "C:\myImage.jpg"
Set img = ws.Pictures.Insert(imagePath)

With img
    .ShapeRange.LockAspectRatio = msoFalse
    .Top = r.Top
    .Left = r.Left
    .Width = r.Width
    .Height = r.Height
End With

But it didn't work out for me, any suggestions?

Best regards, Daniel

1 Answers

if you want to apply code that you've specified in example to selected "Picture 12" then you can use this new example:

Sub selectImage12()
    Dim r As Range
    Dim ws As Worksheet
    Dim img As ShapeRange

    Set ws = Worksheets("T-tilbud")
    Set r = ws.Range("A1:D4")
    
    Set img = ws.Shapes.Range(Array("Picture 12"))

    With img
        .LockAspectRatio = msoFalse
        .Top = r.Top
        .Left = r.Left
        .Width = r.Width
        .Height = r.Height
    End With
End Sub
Related