Excel - A Macro to insert pictures in a worksheet

Ask a question


I'm trying to insert pictures in Excel column using macro which takes the file name refrence from the B2 cell and insert picture in A2 cell. For example: if B2 contains N235 then the picture which will be inserted in A2 would be N235.jpg from the given path in Macro. This is working fine EXCEPT when there is no picture in the folder with the the same name as in folder.
  • I'm getting a runtime error 1004 and Macro stops and can not fill picture after that cell.


Sub Picture()  
Dim picname As String

Dim pasteAt As Integer
Dim lThisRow As Long

lThisRow = 2

Do While (Cells(lThisRow, 2) <> "")

pasteAt = lThisRow
Cells(pasteAt, 1).Select 'This is where picture will be inserted

picname = Cells(lThisRow, 2) 'This is the picture name

present = Dir("C:\Users\Administrator\Desktop\LC\" & picname & ".jpg")

If present <> "" Then

ActiveSheet.Pictures.Insert("C:\Users\Administrator\Desktop\LC\" & picname & ".jpg").Select 'Path to where pictures are stored
' This resizes the picture
With Selection
'.Left = Range("A6").Left
'.Top = Range("A6").Top
.Left = Cells(pasteAt, 1).Left
.Top = Cells(pasteAt, 1).Top

.ShapeRange.LockAspectRatio = msoFalse
.ShapeRange.Height = 100#
.ShapeRange.Width = 130#
.ShapeRange.Rotation = 0#
End With

Cells(pasteAt, 1) = "No Picture Found"
End If

lThisRow = lThisRow + 1

Application.ScreenUpdating = True

Exit Sub

MsgBox "Unable to Find Photo" 'Shows message box if picture not found
Exit Sub

End Sub

Thanks to rizvisa1 for this tip.
Jean-François Pillou

Jean-François Pillou - Founder of CCM
Better known as Jeff, Jean-François Pillou is the founder of CommentCaMarche.net. He is also CEO of CCM Benchmark and digital director at the Figaro Group.

Learn more about the CCM team