VBA Code to Insert an Image in an Excel Cell Automatically

VBA & macros · Updated November 20, 2026

Use VBA’s Shapes.AddPicture method to insert a picture, then position and size it to match a worksheet cell. The macro below places the image over a specified cell, preserves its proportions, and makes it move and resize with that cell.

What “in a cell” means in Excel

Excel pictures have two different behaviors that are easy to confuse. A picture inserted with the VBA code below is a floating object layered over the worksheet grid. It can be aligned with a cell and set to move and resize along with it, but it is not stored as the cell’s value.

Microsoft 365 also offers a newer picture-in-cell feature in supported versions. In the ribbon, look under Insert > Pictures for the option to place a picture in a cell. A true in-cell picture is handled differently from a regular floating picture. The macro here uses the familiar Shapes object model, so it creates a picture over the cell rather than that newer in-cell type. This is useful when you want VBA to control placement and sizing, or when you need the picture to behave like a worksheet object.

VBA code to fit an image over a cell

Change the worksheet name, cell address, and image file path in the code. The picture is inserted at its original proportions, scaled down or up to fit inside the target cell, and centered in the available space. It will not be stretched to fill a cell with a different aspect ratio.

Sub InsertImageOverCell()
    Dim ws As Worksheet
    Dim target As Range
    Dim picture As Shape
    Dim imagePath As String
    Dim scaleFactor As Double

    ' Edit these values for your workbook and image.
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    Set target = ws.Range("B2")
    imagePath = "C:\Images\product.jpg"

    ' Stop with a helpful message if the file path is invalid.
    If Len(Dir$(imagePath)) = 0 Then
        MsgBox "Image file not found: " & imagePath, vbExclamation
        Exit Sub
    End If

    ' -1 requests the picture's original dimensions.
    Set picture = ws.Shapes.AddPicture( _
        Filename:=imagePath, _
        LinkToFile:=msoFalse, _
        SaveWithDocument:=msoTrue, _
        Left:=target.Left, _
        Top:=target.Top, _
        Width:=-1, _
        Height:=-1)

    ' Scale proportionally so the whole picture fits inside the cell.
    picture.LockAspectRatio = msoTrue
    scaleFactor = target.Width / picture.Width
    If target.Height / picture.Height < scaleFactor Then
        scaleFactor = target.Height / picture.Height
    End If
    picture.Width = picture.Width * scaleFactor

    ' Center the picture and keep it tied to the cell's size and position.
    picture.Left = target.Left + (target.Width - picture.Width) / 2
    picture.Top = target.Top + (target.Height - picture.Height) / 2
    picture.Placement = xlMoveAndSize
End Sub

The code uses Excel’s built-in worksheet and shape objects, along with the Office constant msoFalse and Excel’s xlMoveAndSize placement setting. LinkToFile:=msoFalse and SaveWithDocument:=msoTrue embed the image in the workbook rather than relying on a separate linked file. The workbook will therefore grow in size, especially if you add many large images.

How to add and run the macro

  1. Save a copy of your workbook before running any macro. VBA actions cannot be undone with Ctrl+Z.
  2. Save the working file as an Excel Macro-Enabled Workbook (.xlsm) so it can retain VBA code.
  3. Open the Visual Basic Editor. In Excel for Windows, press Alt+F11. On a Mac, try Option+F11; some keyboards require Fn+Option+F11.
  4. In the editor, choose Insert > Module, then paste the code into the new module.
  5. Update Sheet1, B2, and the image path. The path must point to an image file Excel can open.
  6. Return to Excel and run InsertImageOverCell from the Macro dialog, opened with Alt+F8 on Windows. On a Mac, use Tools > Macro > Macros if the keyboard shortcut is unavailable.

Excel for the web can display workbooks containing macros, but it cannot create or run VBA macros. Use the desktop Excel app to edit and run this code. On a Mac, VBA is available in desktop Excel, but file paths use Mac conventions, such as /Users/name/Pictures/product.jpg, rather than a Windows drive path.

How the sizing and placement work

Excel measures a cell’s position and dimensions in points. The macro first inserts the picture at its original size, then locks its aspect ratio so changing its width also adjusts its height proportionally. It calculates a scale factor from both the target cell’s width and height, choosing the smaller factor. That choice ensures the entire picture fits within the cell, even if the cell is unusually narrow or tall.

The centering calculations add half of the remaining horizontal and vertical space to the cell’s left and top positions. For example, if the fitted image is 20 points narrower than the cell, the code leaves 10 points of space on each side. The setting xlMoveAndSize tells Excel to move and resize the floating picture when the underlying cells move or change size. If a row or column is hidden, the picture generally follows the placement behavior associated with that setting.

The image may not cover every part of the cell: preserving its proportions can leave blank space at the sides or top and bottom. That is intentional. Filling every edge would require cropping or distorting the image, and distortion can make logos, faces, or product photos look wrong.

Insert pictures into many rows

For a product list or photo catalog, the same approach can be extended to loop through rows. A typical design keeps each image path in one column and places the corresponding picture in another, such as paths in column C and pictures in column B. The macro can read each path, set the target range to the matching row, and call the same insertion-and-sizing logic for each file.

Before automating a large batch, test with two or three rows. Set a consistent row height and column width first; otherwise, pictures may be fitted into cells of different shapes. If a path is blank or the file is missing, skip that row or report it rather than inserting an unrelated picture. Also decide whether rerunning the macro should add another copy or replace the old picture. The sample macro always adds a new shape, so repeated runs will create duplicates unless you add code to identify and remove existing pictures.

For maintainable workbooks, consider naming each inserted shape using a stable row-based name. A later update routine can then find and replace that specific picture instead of deleting every image on the worksheet. Avoid relying only on a shape’s automatically assigned name, because Excel assigns names as objects are added and those names may not correspond to the related record.

Common problems and their fixes

  • “Image file not found.” Check spelling, the extension, and the full path. On Windows, a path such as C:\Images\product.jpg must refer to an existing file accessible to the current user. A network location may be unavailable when working offline.
  • The macro is blocked. Confirm that the workbook is saved as .xlsm and that you intentionally enable macros for a trusted file. Do not enable macros in an unfamiliar workbook just to view its contents.
  • The picture looks distorted or does not fit. The sample preserves proportions, so blank margins are expected when the cell and image shapes differ. Check that row height and column width are what you intended.
  • The picture stays put when rows change. Confirm that the code sets picture.Placement = xlMoveAndSize. Excel’s other placement choices can make an object move without resizing or remain independent of cell changes.
  • The macro adds duplicates. Each run adds another shape. Delete the previous image manually before rerunning, or modify the macro to look up and replace a specifically named shape.
  • The image is missing on another computer. The sample embeds the picture in the workbook. If you change the code to link to a file instead, recipients must also have access to that same file location.

Floating pictures versus other options

Choose a floating picture when you need VBA to place, resize, name, or otherwise manage image objects. Setting it to move and size with cells makes it useful for reports where row heights and column widths change. The trade-off is that the image remains a separate object, so sorting or filtering a data range may require care to ensure the picture stays associated with the correct record.

Use Excel’s in-cell picture option when the image should behave as content in a cell and your Microsoft 365 version supports that feature. It can be a better fit for image-heavy tables, but it is not what the sample’s Shapes.AddPicture call creates. For a small number of pictures, inserting and positioning them manually may be simpler than maintaining a macro. If pictures need to update from web addresses, Microsoft 365’s IMAGE worksheet function may be an option in supported versions, though it has different requirements and is not a VBA replacement for local-file insertion.

Safety and workbook considerations

VBA can change a workbook immediately, and macro actions cannot be rolled back with Ctrl+Z. Keep a backup, test on a copy, and inspect the selected worksheet and cell before running a batch procedure. A macro that embeds many high-resolution images can make a workbook slow to open, difficult to email, or too large for a particular storage or upload limit.

Use only image files from sources you trust, and keep macro security enabled for files you do not recognize. The sample does not download files or execute code from an image; it checks for a local file and embeds it. If you adapt it to use file pickers, network locations, or automatic deletion, review those changes carefully and test them on disposable data first.

Frequently Asked Questions

Can VBA put a picture inside an Excel cell?
The code here inserts a floating picture positioned over a cell; it does not create Excel’s newer true in-cell picture type. It can still move and resize with the cell. Use the ribbon’s in-cell picture option when you specifically need a picture stored as cell content and your Excel version offers it.

How do I make an image move and resize with a cell?
Set the shape’s Placement property to xlMoveAndSize. The sample applies this after positioning the image. The picture then responds to changes in the cells beneath it rather than behaving as a completely independent object.

Why does the macro leave blank space around the image?
It preserves the image’s aspect ratio and fits the whole picture inside the cell. If the cell has a different width-to-height ratio, empty space remains. Cropping or stretching can fill more of the cell, but may remove content or distort the picture.

Can I use this macro in Excel for the web?
No. Excel for the web does not run VBA. Open the workbook in desktop Excel for Windows or Mac to add and run the macro; the web app can display the workbook but cannot execute this procedure.

How do I insert a different image for every row?
Store each image’s file path in a worksheet column, loop through the rows in VBA, and insert each file over the target cell in that row. Add checks for empty or invalid paths and decide how the macro will replace pictures when it is run again.

Related

Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.

More in VBA & macros

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.