To insert an image with Excel VBA, call the worksheet’s Shapes.AddPicture method, supplying the image file path and its position. Use LinkToFile:=msoFalse and SaveWithDocument:=msoTrue to embed the image in the workbook, so it does not depend on the original file staying in the same location.
What VBA Adds to the Worksheet
Excel displays an inserted picture as a shape layered over the worksheet grid. It can be positioned over a cell or a group of cells, but it is not stored inside a cell like text or a number. This matters when you sort rows, change column widths, or expect a picture to behave like cell content: its behavior depends on the shape’s placement setting.
Shapes.AddPicture creates the picture and returns a Shape object. The method accepts the image path, link and save options, and position and size in points. A point is a typographic measurement equal to 1/72 of an inch. Using a cell’s Left, Top, Width, and Height properties is an easy way to align a picture with the grid.
The example below places a picture within cell B2, keeps its proportions, and centers it in the cell. Change the worksheet name, cell address, and file path to match your workbook. The file path shown is an example; it must point to an image that exists on the computer running the macro.
Insert and Fit One Image
Save a copy of the workbook before running a macro: VBA changes cannot be reversed with Ctrl+Z. The code uses a common image format such as PNG or JPEG and embeds the image rather than linking to it.
Sub InsertPictureAtCell()
Dim ws As Worksheet
Dim target As Range
Dim pic As Shape
Dim filePath As String
' Set these to the worksheet, cell, and image you want.
filePath = "C:\Images\product.jpg"
Set ws = ThisWorkbook.Worksheets("Sheet1")
Set target = ws.Range("B2")
' Stop with a message if the path does not exist.
If Len(Dir$(filePath)) = 0 Then
MsgBox "Image file not found: " & filePath, vbExclamation
Exit Sub
End If
' -1 for width and height uses the picture's original dimensions.
Set pic = ws.Shapes.AddPicture( _
Filename:=filePath, _
LinkToFile:=msoFalse, _
SaveWithDocument:=msoTrue, _
Left:=target.Left, _
Top:=target.Top, _
Width:=-1, _
Height:=-1)
' Scale proportionally to fit inside the target cell.
pic.LockAspectRatio = msoTrue
If pic.Width / pic.Height > target.Width / target.Height Then
pic.Width = target.Width
Else
pic.Height = target.Height
End If
' Center the picture and make it follow cell changes.
pic.Left = target.Left + (target.Width - pic.Width) / 2
pic.Top = target.Top + (target.Height - pic.Height) / 2
pic.Placement = xlMoveAndSize
End Sub
In the code, Width:=-1 and Height:=-1 ask Excel to use the image’s original size when it is created. The macro then locks the aspect ratio and reduces either the width or height to fit the target cell. It does not stretch the picture to fill every corner; leaving empty space on one side is the normal result when the image and cell have different proportions.
Put the Macro in Excel and Run It
- Save the workbook as an Excel Macro-Enabled Workbook (
.xlsm) if you want to keep the VBA code in it. - Open the Visual Basic Editor with Alt+F11 on Windows. In the editor, choose Insert > Module, then paste the macro into the module.
- Update the file path and worksheet name in the code. Make sure the worksheet exists and the image file can be opened from that path.
- Return to Excel, select Developer > Macros, choose
InsertPictureAtCell, and select Run. If the Developer tab is hidden, enable it through File > Options > Customize Ribbon.
Excel may show a security warning or block macros, depending on the workbook’s source and your organization’s settings. Only enable macros in files you trust. Saving as .xlsx does not preserve VBA; Excel warns that macro code will be removed if you save a macro-containing workbook in that format.
Choose How the Picture Relates to Cells
The final line, pic.Placement = xlMoveAndSize, makes the picture move and resize with the cells beneath it. Excel also offers xlMove, which moves the picture with cells but does not resize it, and xlFreeFloating, which leaves it independent of cell changes. These choices are useful in different layouts:
- Use
xlMoveAndSizewhen each picture belongs to a row and should follow that row as columns or row heights change. - Use
xlMovewhen sorting or moving rows should carry pictures along, but you do not want cell resizing to resize them. - Use
xlFreeFloatingfor a decorative image or diagram positioned independently of the table.
These settings do not put an image inside a cell. They control how a shape responds to changes in the grid. If a picture must stay aligned with records during sorting, test the workbook’s sort and filter behavior with a copy first. Consistent row heights and one picture per row make the layout easier to maintain.
Embedded Pictures Versus Linked Pictures
The two AddPicture arguments that control storage are LinkToFile and SaveWithDocument. In the main example, msoFalse for the link and msoTrue for saving with the workbook create an embedded picture. The workbook contains the image data, so it can travel without the original image file, though embedding images increases workbook size.
A linked picture can reduce duplication when many workbooks refer to the same image, but it relies on a file at a location Excel can still reach. Moving or renaming that file, changing a network connection, or sharing the workbook with someone who lacks access can break the link. If you choose linking, test the workbook from the other computer or folder where it will be used. For a self-contained workbook, embedding is usually the simpler choice.
Insert Pictures for Several Rows
For a product list or photo register, store one full image path in column A for each record, starting in A2, and use column B as the picture area. A loop can read each path, place the corresponding image in column B of the same row, and skip blank or missing paths. This keeps the mapping visible in the worksheet and avoids hard-coding every file name separately.
Save a copy before running a batch macro, since adding many pictures can take time and cannot be undone with Ctrl+Z. The following example embeds each image and fits it proportionally into its row’s column B cell. Adjust the sheet name and columns if your table is arranged differently.
Sub InsertPicturesFromColumnA()
Dim ws As Worksheet
Dim lastRow As Long
Dim r As Long
Dim filePath As String
Dim target As Range
Dim pic As Shape
Set ws = ThisWorkbook.Worksheets("Sheet1")
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
For r = 2 To lastRow
filePath = Trim$(CStr(ws.Cells(r, "A").Value))
If Len(filePath) > 0 And Len(Dir$(filePath)) > 0 Then
Set target = ws.Cells(r, "B")
Set pic = ws.Shapes.AddPicture( _
Filename:=filePath, _
LinkToFile:=msoFalse, _
SaveWithDocument:=msoTrue, _
Left:=target.Left, Top:=target.Top, _
Width:=-1, Height:=-1)
pic.LockAspectRatio = msoTrue
If pic.Width / pic.Height > target.Width / target.Height Then
pic.Width = target.Width
Else
pic.Height = target.Height
End If
pic.Left = target.Left + (target.Width - pic.Width) / 2
pic.Top = target.Top + (target.Height - pic.Height) / 2
pic.Placement = xlMoveAndSize
End If
Next r
End Sub
This code skips empty cells and paths that do not resolve to a file, but it does not report which rows were skipped. For a production workflow, consider writing a status such as “Missing image” in another column, and decide how the macro should handle rows that already contain pictures before running it again. Otherwise, a second run can create duplicate shapes.
Common Problems and Fixes
- File not found: Check spelling, extension, and folder. A path such as
C:\Images\product.jpgis specific to a Windows folder; a different computer may use a different drive or directory. - Subscript out of range: The worksheet name in
Worksheets("Sheet1")does not match a sheet tab in the workbook referenced byThisWorkbook. Use the exact tab name. - Picture is too large or cropped: A simple assignment of both width and height can distort the image. Lock the aspect ratio and fit it inside the target bounds, as in the examples.
- Picture does not follow a row: Set the shape’s
Placementproperty to the behavior you want. Also check whether sorting the records rearranges pictures as expected. - Macro does not run: Confirm the workbook is saved as
.xlsm, the macro is allowed by your security settings, and the procedure is in a standard module.
Another common misconception is that inserting an image into a cell makes it part of that cell’s value. It does not: Excel treats the picture as a separate shape. Newer Excel releases have features for placing pictures in cells through the interface, but those are distinct from this traditional VBA method, which creates a worksheet shape.
Windows, Mac, and Excel for the Web
The code is written for desktop Excel on Windows. Excel for Mac also supports VBA and worksheet shapes, but file paths differ: a Windows path beginning with a drive letter will not point to the same file on a Mac. Use a valid Mac path and check that the image is accessible from that machine. The VBA editor shortcut can also depend on the Mac keyboard; Option+F11 or Fn+Option+F11 may be needed. You can open the editor from Excel’s Tools or Developer menu if the shortcut does not work.
Excel for the web does not run VBA macros. A workbook containing VBA can be opened there, but run the macro in desktop Excel. If users need to insert pictures in a browser, use the web interface or an appropriate automation approach rather than expecting VBA to execute online.
Frequently Asked Questions
How do I insert an image into a specific Excel cell with VBA?
Use Shapes.AddPicture and set its Left and Top to the target range’s position. Fit and center the shape using the cell’s width and height, then set Placement to control how it responds to cell changes.
Does VBA put the picture inside the cell?
No. The picture is a separate shape positioned over the worksheet grid. Placement options can make it move or resize with cells, but it is not the cell’s stored value.
How can I keep the image’s original proportions?
Set pic.LockAspectRatio = msoTrue, then change only its width or only its height to fit the available area. Avoid independently assigning both dimensions unless you intend to stretch the image.
Can I insert a picture without a file path?Shapes.AddPicture needs an image file path. A file picker can be used to let someone choose that path at run time, but the basic method still needs a selected, accessible image file.
Can Excel for the web run an image-inserting VBA macro?
No. Run VBA in desktop Excel for Windows or Mac. Excel for the web can display a workbook, but it does not execute VBA macros.
Related
- Excel Template for a Social Media Calendar
- Excel Job List Template: Track Applications and Follow-Ups
- Excel To-Do List Templates: How to Choose and Use One
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel VBA Create Dictionary: Setup, Code, and Practical TipsTo create a Dictionary in Excel VBA on Windows, declare an object and set it to CreateObject("Scripting.Dictionary"). You…
- Find Unique Values in VBA: Methods and ExamplesTo find distinct values in VBA, read the source cells into a Scripting.Dictionary and add a value only…
- VBA Delete Active Row: Simple Macro, Safety, and TipsTo delete the worksheet row containing the active cell in Excel VBA, call the row’s Delete method. The…
- Excel Analysis ToolPak vs ToolPak VBA: Key DifferencesExcel’s Analysis ToolPak is the add-in for running built-in statistical and engineering analyses from the Data tab; Analysis…
- Excel VBA Find Numbers Only: Code, Search Tips, and FixesYes. To find cells that contain real numeric values—not numbers stored as text—loop through the range and check…
- Excel VBA: Find the Minimum Value in a Range or ArrayTo find a range’s minimum in Excel VBA, use Application.WorksheetFunction.Min, for example, Application.WorksheetFunction.Min(Range("B2:B20")). For a macro you can…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.