Search code examples
excelvbasharepoint

How to use VBA to insert a photo IN a cell


I have an excel file that displays a sorted table.

The way I’m doing this is copying over rows that match the search criteria. However, Some of the cells contain pictures which makes this more annoying.

Currently the code works for photos that have been manually inserted INTO a cell. However, whenever I try to use VBA to replace placeholder text in a cell it just places the photo OVER the cell. Is there any way to mimic placing a photo IN a cell with VBA?


Solution

    • For M365
    Sub InsertPicM365()
        Range("A1").InsertPictureInCell "C:\Pictures\image.png"
    End Sub
    
    • For other version Excel
    Sub InsertPic()
        Dim oShp As Object, iW As Double, iH As Double
        Const IMAGE = "C:\Pictures\image.png"
        Const CELL = "A1"
        ' insert image
        Set oShp = ActiveSheet.Pictures.Insert(IMAGE)
        With Range(CELL)
            ' get the shrink/enlarge ratio
            iW = .Width / oShp.Width
            iH = .Height / oShp.Height
            ' shrink/enlarge image
            oShp.ShapeRange.ScaleWidth IIf(iW < iH, iW, iH), msoFalse, msoScaleFromTopLeft
            ' relocate image
            oShp.Top = .Top + (.Height - oShp.Height) / 2
            oShp.Left = .Left + (.Width - oShp.Width) / 2
        End With
    End Sub