How to Insert and Fit a Picture into a Selected Cell Using Excel VBA



Sub SelectAndFitPictureToCell()
    Dim ws As Worksheet
    Dim imgPath As String
    Dim img As Picture
    Dim targetCell As Range
    Dim targetWidth As Double
    Dim targetHeight As Double
    
    ' Set the worksheet to the active sheet
    Set ws = ThisWorkbook.ActiveSheet
    
    ' Set the target cell to the currently selected cell
    Set targetCell = ActiveCell
    
    ' Open the file dialog to select an image
    imgPath = Application.GetOpenFilename("Image Files (*.jpg; *.jpeg; *.png; *.gif), *.jpg; *.jpeg; *.png; *.gif", , "Select an Image")
    
    ' If no file was selected, exit the sub
    If imgPath = "False" Then Exit Sub
    
    ' Insert the image into the sheet
    Set img = ws.Pictures.Insert(imgPath)
    
    ' Get the target cell's width and height
    targetWidth = targetCell.Width
    targetHeight = targetCell.Height
    
    ' Resize the image to fit the target cell's size
    With img
        .ShapeRange.LockAspectRatio = msoFalse ' Allow resizing without preserving aspect ratio
        .Width = targetWidth
        .Height = targetHeight
        .Top = targetCell.Top
        .Left = targetCell.Left
    End With
End Sub

Comments