Excel VBA Insert Images From Image Name in Column

前端 未结 1 727
無奈伤痛
無奈伤痛 2020-12-11 14:16

Been reading a lot if different threads about inserting images and re-sizing them but cannot find one that does exactly what I want it to do.

So say I have a spreads

1条回答
  •  时光说笑
    2020-12-11 15:13

    Here is a sample that will iterate over a range of cells (B1:B100) which you can modify, and uses the filename from the cell one column to the left (so, from Column A), and sizes the image to fit within cell in column B.

    Sub InsertPic()
    Dim pic As String 'file path of pic
    Dim myPicture As Picture 'embedded pic
    Dim rng As Range 'range over which we will iterate
    Dim cl As Range 'iterator
    
    Set rng = Range("B7:B7")
    For Each cl In rng
        pic = cl.Offset(0, -1)
    
            Set myPicture = ActiveSheet.Pictures.Insert(pic)
            '
            With myPicture
                .ShapeRange.LockAspectRatio = msoFalse
                .Width = cl.Width
                .Height = cl.Height
                .Top = Rows(cl.Row).Top
                .Left = Columns(cl.Column).Left
            End With
            '
    
    Next
    
    End Sub
    

    There is no error-handling in this code to account for invalid filenames, you will probably want to add that.

    0 讨论(0)
提交回复
热议问题