Hi,
The code below prompts the user to select an image file and a cell to paste the image to. Attached is the sample file with the macro.
Issue: When I run the macro, an error message pops up "Run time error 1004 - Application defined or object defined error." and when I click on Debug, the code line ".Placement = xlMoveAndSize" is highlighted. The selected image do get pasted but in an enlarged size without xlMoveAndSize.
If I click End multiple times and run the macro again, the image fits into the cell as required.
Quite weird. I have no idea what is going wrong.
Request help to sort this issue.
The code below prompts the user to select an image file and a cell to paste the image to. Attached is the sample file with the macro.
Issue: When I run the macro, an error message pops up "Run time error 1004 - Application defined or object defined error." and when I click on Debug, the code line ".Placement = xlMoveAndSize" is highlighted. The selected image do get pasted but in an enlarged size without xlMoveAndSize.
If I click End multiple times and run the macro again, the image fits into the cell as required.
Quite weird. I have no idea what is going wrong.
Request help to sort this issue.
Code:
Option Explicit
Sub FitPic()
' Keyboard Shortcut: Ctrl+Shift+P
Dim sFile As Variant, r As Range
sFile = Application.GetOpenFilename(FileFilter:="Pic Files (*.jpg;*.bmp), *.jpg;*.bmp", Title:="Browse to select a picture")
If sFile = False Then Exit Sub
On Error Resume Next
Set r = Application.InputBox("Click in the cell to hold the picture", Type:=8)
On Error GoTo 0
If r Is Nothing Then Exit Sub
If r.Count > 1 Then Exit Sub
ActiveSheet.Pictures.Insert (sFile)
With ActiveSheet.Shapes(ActiveSheet.Shapes.Count)
.LockAspectRatio = True
.Top = r.Top
.Left = r.Left
.Height = r.RowHeight
.Placement = xlMoveAndSize
End With
End Sub