To center an image in an Excel cell with VBA, select the picture, run a macro that scales it to fit the cell while preserving its aspect ratio, and set its position to the cell’s midpoint. Excel pictures are floating objects rather than cell contents, so the macro aligns the picture over the cell and can make it move or resize with the cell.
What “in a cell” means in Excel
A picture inserted on a worksheet is a shape layered above the grid. It does not become a value inside a cell in the way text or a number does. This distinction matters: a picture can cover several cells, sit partly outside the grid, or overlap other objects. VBA can set its position and size to match a cell, but it cannot turn an ordinary floating picture into a cell value.
For most worksheets, matching the image’s edges to the cell’s boundaries and centering it within those boundaries gives the result people mean by “put an image in a cell.” The VBA properties used for that are Left, Top, Width, and Height. Excel measures these dimensions in points. A cell’s position and dimensions are available through the corresponding range properties.
Excel for Microsoft 365 also has newer picture-in-cell features in some builds. Those pictures behave differently from ordinary floating pictures, and a macro that expects a selected shape may not apply to them in the same way. The code below is for a conventional inserted picture or other selected shape.
A macro to center the selected picture
This macro takes the currently selected shape, asks for a destination cell on the active worksheet, scales the shape down if needed, and centers it. It preserves the image’s proportions and does not enlarge a small image. If the destination is a merged cell, it uses the entire merged area as the target.
Sub CenterSelectedPictureInCell()
Dim shp As Shape
Dim target As Range
Dim address As Variant
Dim scaleFactor As Double
' The picture must be selected before the macro runs.
On Error Resume Next
Set shp = Selection.ShapeRange(1)
On Error GoTo 0
If shp Is Nothing Then
MsgBox "Select one picture or shape first.", vbExclamation
Exit Sub
End If
' Enter a cell address on the active worksheet, such as B4.
address = Application.InputBox( _
Prompt:="Enter the destination cell address:", _
Title:="Center picture in cell", _
Default:=ActiveCell.Address(False, False), Type:=2)
If VarType(address) = vbBoolean Then Exit Sub
On Error Resume Next
Set target = ActiveSheet.Range(CStr(address))
On Error GoTo 0
If target Is Nothing Then
MsgBox "That cell address is not valid on the active sheet.", vbExclamation
Exit Sub
End If
If target.Cells.CountLarge > 1 And Not target.MergeCells Then
MsgBox "Enter one cell, or the top-left cell of a merged area.", vbExclamation
Exit Sub
End If
If target.MergeCells Then Set target = target.MergeArea
If target.Width <= 0 Or target.Height <= 0 Then
MsgBox "The target cell has no visible width or height.", vbExclamation
Exit Sub
End If
' Use the smaller scale needed to fit; never enlarge the picture.
scaleFactor = target.Width / shp.Width
If target.Height / shp.Height < scaleFactor Then
scaleFactor = target.Height / shp.Height
End If
If scaleFactor > 1 Then scaleFactor = 1
With shp
.LockAspectRatio = msoTrue
.Width = .Width * scaleFactor
.Left = target.Left + (target.Width - .Width) / 2
.Top = target.Top + (target.Height - .Height) / 2
.Placement = xlMoveAndSize
End With
End Sub
The scale calculation compares the cell’s width-to-picture-width ratio with its height-to-picture-height ratio, then uses the smaller value. That keeps the whole image inside the target without stretching it. For example, if a picture is 120 points wide and 80 points high, and the cell is 60 by 40 points, the scale is 0.5. The result is a 60-by-40-point picture centered in the cell. If the cell is larger than the picture in both dimensions, the macro leaves the picture at its original size and centers it with space around it.
How to add and run the VBA macro
- Save a copy of the workbook before running a macro. VBA actions cannot be reversed with Ctrl+Z.
- In desktop Excel for Windows, press Alt+F11 to open the Visual Basic Editor. On a Mac, the shortcut is usually Option+F11; depending on the keyboard, you may also need the Fn key.
- In the editor, choose Insert > Module, then paste the code into the new module.
- Return to the worksheet and select the picture. Run the macro from Developer > Macros, choose
CenterSelectedPictureInCell, and select Run. - Enter the destination address, such as
B4, in the prompt. The address refers to the active worksheet, so confirm that the correct sheet is active.
If the Developer tab is not visible in Windows Excel, enable it through File > Options > Customize Ribbon and check Developer. On Mac, use Excel > Preferences or Settings > Ribbon & Toolbar, depending on the release, to show the tab. Save a workbook containing VBA as an Excel Macro-Enabled Workbook (.xlsm); saving it as a standard .xlsx file removes the VBA project. Excel for the web can open a macro-enabled workbook, but it cannot run VBA macros.
Centering, fitting, and cropping are different
Centering sets the picture’s midpoint to the cell’s midpoint. Fitting controls whether the full picture stays within the cell. Cropping fills a chosen area by trimming part of the picture. The example macro fits and centers; it does not crop. A wide photo in a tall, narrow cell will therefore have empty space above and below, while a tall photo in a wide cell will have empty space at the sides.
That result is often best for product thumbnails, profile photos, or reference images where no part of the subject should be cut off. If every cell needs to look filled edge to edge, cropping may be preferable, but it requires a different approach. Simply changing the picture’s width and height independently can fill the cell, but it distorts the image. Keep LockAspectRatio enabled when accurate proportions matter.
The code also avoids enlarging small pictures. Upscaling can make a low-resolution image look blurry, so leaving it at its original dimensions is a useful default. If you do want small images enlarged to fill a cell, remove the line that caps scaleFactor at 1. The image will still keep its proportions, though enlargement cannot add detail that was not in the source.
What the placement setting changes
The final line, .Placement = xlMoveAndSize, tells Excel to move and resize the shape with its associated cells. This is useful when rows or columns are adjusted, or when the worksheet is sorted or filtered. It makes the picture behave more like part of the cell’s layout, but does not convert it into cell data.
There are trade-offs. When the row height or column width changes, Excel may resize the picture along with the cell, and that change can affect the picture’s appearance. If you want the picture to move with a cell but keep its size, use xlMove instead. If you want it to stay fixed on the sheet regardless of cell changes, use xlFreeFloating. Those alternatives change the anchoring behavior; they do not automatically recenter the picture after a layout change. Run the centering macro again if the picture no longer appears centered.
For worksheets that are frequently resized, filtered, or sorted, check the result after changing the layout. Pictures are anchored to worksheet coordinates, and merged cells can make sorting or filtering less straightforward. For a stable thumbnail table, consistent row heights and column widths usually make the layout easier to maintain.
Common problems and how to fix them
- “Select one picture or shape first” appears: Excel did not expose a selected shape to the macro. Click the picture’s border rather than a cell, then run the macro again. If you selected a picture-in-cell feature rather than a floating picture, use the controls available for that feature instead.
- The image is centered in the wrong place: The prompt uses the active worksheet, and the default address comes from the active cell. Enter the intended cell address explicitly and make sure you are on the correct sheet.
- The picture looks stretched after changing row or column sizes: The macro preserves proportions when it initially scales the picture. However, resizing associated cells under
xlMoveAndSizecan change the result. TryxlMoveand rerun the macro after changing the layout. - The picture seems clipped or does not fit: Check whether the row or column is hidden, whether the target is merged, and whether the image has a visible border or shadow that makes its bounds appear larger. Unhide the row or column and check the target dimensions.
- The macro is missing or blocked: Confirm the file is saved as
.xlsmand that macros are permitted by your organization’s security settings. Do not enable macros in files from untrusted sources merely to make a picture adjustment.
When VBA is useful—and when it is not
VBA is useful when many pictures need consistent alignment, when a repeated report is generated, or when images must be repositioned after a process adds them. The sample macro handles one selected shape per run. A bulk macro could loop through worksheet shapes and match each one to a cell, but that requires a reliable rule for identifying each picture’s target, such as its name, row, or position. Guessing based only on overlap can produce unexpected results when pictures cover multiple cells.
For a single image, a manual adjustment may be faster: select the picture and drag it into place, or use the Size & Properties pane to control its dimensions and placement. Excel’s alignment commands can help align multiple selected objects with each other, but they do not automatically center each image inside a different cell. If your Excel build offers a picture-in-cell command, that feature may be a more direct option for simple grids because it is designed to associate an image with a cell rather than merely anchor a floating shape over it.
Choose the method based on the task. Use a floating picture plus VBA when you need repeatable positioning or compatibility with a macro-driven workflow. Use manual placement for one-off visuals. Consider a native picture-in-cell feature when it is available and the picture should behave as cell content. In every case, test sorting, filtering, resizing, and printing on a copy before applying the layout to a large or important workbook.
Frequently Asked Questions
Can I center a picture in a cell without VBA?
Yes. Resize and position the floating picture manually, using the cell edges as guides. For repeated work, a VBA macro is more consistent. If your Excel version has a picture-in-cell feature, you can use that instead of positioning a floating shape.
Does the macro center the image without stretching it?
Yes. It sets LockAspectRatio to true and scales the image uniformly. It fits the picture inside the cell and does not enlarge a picture that is already smaller than the target in both dimensions.
Can I use this macro for a merged cell?
Yes. Enter the address of a cell in the merged area. The macro uses the full merged area’s width and height for centering. Avoid entering an unrelated multi-cell range; the code is intended for one cell or a merged cell area.
Will the picture stay centered if I change the cell size?
Not necessarily. The macro centers it at the time it runs. The xlMoveAndSize setting makes the picture move and resize with cells, but a later row-height or column-width change may alter its alignment or proportions. Run the macro again, or use xlMove if retaining the picture’s size is more important.
Can Excel for the web run this VBA code?
No. Excel for the web does not run VBA macros. Open the workbook in the desktop version of Excel for Windows or Mac to use the Visual Basic Editor and run the macro.
Related
- Excel Shortcut to Select to the End of a Column
- Excel Shortcut to Select Cells to the End of a Column
- Excel Shortcut to Select the Active Cell’s Entire Column
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- VBA Quotes in Strings: How to Include Double QuotesTo put a double quote inside a VBA string, double it: write "" inside the surrounding string literal.…
- UserForm VBA Properties: What They Do and How to Set ThemUserForm VBA properties control a form’s identity, appearance, size, position, and behavior in an Excel desktop workbook. You…
- Excel VBA Weekday: Syntax, Return Values, and ExamplesIn Excel VBA, use Weekday(date, firstdayofweek) to get a date’s position in the week as a number from…
- VBA InputBox Integer: Get and Validate Whole NumbersVBA’s standard InputBox returns text, not an Integer. In Excel VBA, use Application.InputBox with Type:=1 to request a…
- Excel VBA Copy Paste Transpose: Working Code and TipsTo copy a range and paste it transposed with Excel VBA, copy the source range and use PasteSpecial…
- VBA Range Filter: How to Use AutoFilterTo filter a worksheet range with VBA in Excel for Microsoft 365 on Windows, call the range’s AutoFilter…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.