How to insert a picture into Excel at a specified cell position with VBA
Try this:
With xlApp.ActiveSheet.Pictures.Insert(PicPath) With .ShapeRange .LockAspectRatio = msoTrue .Width = 75 .Height = 100 End With .Left = xlApp.ActiveSheet.Cells(i, 20).Left .Top = xlApp.ActiveSheet.Cells(i, 20).Top .Placement = 1 .PrintObject = TrueEnd With
It's better not to .select anything in Excel, it is usually never necessary and slows down your code.
Looking at posted answers I think this code would be also an alternative for someone. Nobody above used .Shapes.AddPicture
in their code, only .Pictures.Insert()
Dim myPic As ObjectDim picpath As Stringpicpath = "C:\Users\photo.jpg" 'example photo pathSet myPic = ws.Shapes.AddPicture(picpath, False, True, 20, 20, -1, -1)With myPic .Width = 25 .Height = 25 .Top = xlApp.Cells(i, 20).Top 'according to variables from correct answer .Left = xlApp.Cells(i, 20).Left .LockAspectRatio = msoFalseEnd With
I'm working in Excel 2013. Also realized that You need to fill all the parameters in .AddPicture
, because of error "Argument not optional". Looking at this You may ask why I set Height
and Width
as -1, but that doesn't matter cause of those parameters are set underneath between With
brackets.
Hope it may be also useful for someone :)
If it's simply about inserting and resizing a picture, try the code below.
For the specific question you asked, the property TopLeftCell returns the range object related to the cell where the top left corner is parked. To place a new image at a specific place, I recommend creating an image at the "right" place and registering its top and left properties values of the dummy onto double variables.
Insert your Pic assigned to a variable to easily change its name. The Shape Object will have that same name as the Picture Object.
Sub Insert_Pic_From_File(PicPath as string, wsDestination as worksheet) Dim Pic As Picture, Shp as Shape Set Pic = wsDestination.Pictures.Insert(FilePath) Pic.Name = "myPicture" 'Strongly recommend using a FileSystemObject.FileExists method to check if the path is good before executing the previous command Set Shp = wsDestination.Shapes("myPicture") With Shp .Height = 100 .Width = 75 .LockAspectRatio = msoTrue 'Put this later so that changing height doesn't change width and vice-versa) .Placement = 1 .Top = 100 .Left = 100 End withEnd Sub
Good luck!