The issue you're facing where some images insert correctly, but most become tiny and appear in the wrong column is quite common when working with Pictures.Insert in VBA. This behavior is often caused by a combination of factors related to image resizing, cell dimensions, and Excel's rendering quirks. Let's break down the potential reasons and provide a robust solution to fix this:
Root Causes of the Problem:
-
Excel's Auto-Scaling Bug:
- When you set
.Width = targetCell.Width, Excel sometimes miscalculates the image's aspect ratio or applies an unintended secondary scaling (especially if the image's original dimensions are much larger than the cell).
- This causes the image to shrink disproportionately and misalign.
-
Floating-Point Precision Issues:
- VBA's
.Left and .Top properties use points (1/72 of an inch), not pixels. If Excel's zoom level or screen resolution differs, positioning can go haywire.
- When
.Width is set too small (e.g., a cell width of 15 points ≈ 110 pixels), large images collapse to nearly zero height, making them invisible or misplaced.
-
Column/Row Dimension Mismatches:
- If row heights aren't adjusted dynamically, tall images overflow into neighboring rows/columns.
- If column widths aren't consistent (due to screen zoom or manual resizing),
.Left calculations fail.
-
Image Metadata Quirks:
- Some image formats (e.g.,
.jfif) embed DPI metadata that Excel misinterprets, leading to wonky scaling.
- Images with non-standard aspect ratios (e.g., super-wide banners) distort when forced into a square-ish cell.
-
ScreenUpdating Behavior:
- Rapidly inserting and resizing images without full screen refreshes can confuse Excel's rendering engine.
Debugged & Robust Solution:
Here's an enhanced version of your code with explicit controls to prevent these issues:
Sub AngelInsertImages()
Dim ws As Worksheet
Dim imgName As String
Dim cell As Range
Dim pic As Picture
Dim imageFolder As String
Dim fullImagePath As String
Dim extensions As Variant
Dim ext As Variant
Dim imageFound As Boolean
Dim targetCell As Range
Dim maxWidth As Double
Dim aspectRatio As Double
Set ws = ThisWorkbook.Sheets("Acc List")
imageFolder = "\\Apac\hkdl\data\Merchandise\Common\Internal Share\Product Photo\Pic with white background\Accessories\"
extensions = Array(".jfif", ".jpg", ".png")
Application.ScreenUpdating = False
' Set fixed column width (ensure consistency)
ws.Columns("F").ColumnWidth = 15
maxWidth = ws.Columns("F").Width ' Points (not pixels)
For Each cell In ws.Range("G2:G" & ws.Cells(ws.Rows.Count, "G").End(xlUp).Row)
imgName = Trim(cell.Value)
imageFound = False
For Each ext In extensions
fullImagePath = imageFolder & imgName & ext
If Dir(fullImagePath) <> "" Then
imageFound = True
Exit For
End If
Next ext
If imageFound Then
Set targetCell = ws.Cells(cell.Row, "F")
Set pic = ws.Pictures.Insert(fullImagePath)
' 1. Capture original dimensions BEFORE resizing
aspectRatio = pic.Height / pic.Width
' 2. Resize image to fit cell width (hard limit)
pic.Width = maxWidth - 4 ' Leave 2px padding left/right
' 3. Scale height using the original aspect ratio
pic.Height = pic.Width * aspectRatio
' 4. EXPLICITLY POSITION IN TARGET CELL (overcome floating-point drift)
pic.Left = targetCell.Left + (targetCell.Width - pic.Width) / 2 ' Center horizontally
pic.Top = targetCell.Top + (targetCell.Height - pic.Height) / 2 ' Center vertically
' 5. Adjust row height dynamically if image overflows
If pic.Height > targetCell.Height Then
targetCell.RowHeight = pic.Height + 4 ' Add padding
End If
pic.Placement = xlMoveAndSize ' Lock to cell
Else
Debug.Print "Image not found: " & imgName & " in row " & cell.Row
End If
Next cell
' Force-refresh Excel's layout
Application.ScreenUpdating = True
Application.ScreenUpdating = False
Application.ScreenUpdating = True
MsgBox "Images inserted and formatted!", vbInformation
End Sub
What's changed?
- Pre-calculate
aspectRatio before resizing .Width. This ensures .Height scales correctly.
- Center images in the cell (horizontally/vertically) to avoid drift into neighboring columns/rows.
- Force row height adjustment if the image exceeds the cell's natural height.
- Minor padding (4 pixels total) prevents images from touching cell borders.
- Double
ScreenUpdating toggle at the end forces Excel to redraw all shapes cleanly.
Troubleshooting Tips:
- Check image sizes: If original images are HUGE (e.g., 4000x3000 px), Excel might struggle. Resize them externally to ~500x500 px max.
- Verify file paths: Ensure
Dir(fullImagePath) returns valid files. Missing/bad images cause weird behavior.
- Test on a small subset (e.g., rows 2-5) before running on the full dataset.
This should resolve 99% of misplacement issues. If problems persist:
- Confirm your screen resolution/zoom is 100% in Excel.
- Check if corrupted images exist in the folder (try re-saving them).
- Run
Application.CommandBars.ExecuteMso "PictureReset" in the Immediate Window (Ctrl+G) to reset all image metadata.
Happy debugging! Let me know if this version works flawlessly.