• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Error While Importing Images VBA

titanunleashed

New Member
Hi,
Please help resolve below error; I am using below mentioned VBA:

79952

>>> use code - tags <<<
Code:
Sub Imager()
'
' Imager Macro
'
' Keyboard Shortcut: Ctrl+j
'
Dim fPath As String, fName As String
Dim r As Range, rng As Range
Dim shpPic As Shape

Application.ScreenUpdating = False
fPath = "D:\Images\"
Set rng = Range("D2:D" & Cells(Rows.Count, 4).End(xlUp).Row)
For Each r In rng
    On Error GoTo errHandler
    If r.Value <> "" Then
        Set shpPic = ActiveSheet.Shapes.AddPicture(Filename:=fPath & r.Value & ".jpg", linktofile:=msoFalse, _
            savewithdocument:=msoTrue, Left:=Cells(r.Row, 2).Left, Top:=Cells(r.Row, 2).Top, Width:=-10, Height:=-10)
        With shpPic
            .LockAspectRatio = msoTrue
            If .Width > Columns(2).Width Then .Width = Columns(2).Width
            Rows(r.Row).RowHeight = .Height
        End With
    End If
errHandler:
If Err.Number <> 0 Then
    Debug.Print Err.Number & ", " & Err.Description & ", " & r.Value
    On Error GoTo -1
End If
Next r
Application.ScreenUpdating = True

End Sub
 

Attachments

  • 1657654997321.png
    1657654997321.png
    9 KB · Views: 1
Last edited by a moderator:
Try something like this:

Code:
Sub Imager()
'
' Imager Macro
'
' Keyboard Shortcut: Ctrl+j
'
   Dim fPath As String
   Dim r As Range, rng As Range
  
   Application.ScreenUpdating = False
  
   fPath = "D:\Images\"
  
   Set rng = Range("D2:D" & Cells(Rows.Count, 4).End(xlUp).Row)
  
   For Each r In rng
  
      If r.Value <> "" Then InsertPicture fPath & r.Value & ".jpg", r.Row, 2
      
   Next r
  
   Application.ScreenUpdating = True

End Sub
Sub InsertPicture(pictureFile As String, rwNum As Long, colNum As Long)
   Dim shpPic As Shape

   If Dir(pictureFile) <> vbNullString Then
      On Error Resume Next
      Set shpPic = ActiveSheet.Shapes.AddPicture(Filename:=pictureFile, linktofile:=msoFalse, _
      savewithdocument:=msoTrue, Left:=Cells(rwNum, colNum).Left, Top:=Cells(rwNum, colNum).Top, Width:=-10, Height:=-10)
      If shpPic Is Nothing Then
         Debug.Print Err.Number & ", " & Err.Description & ", " & pictureFile
         Err.Clear
      Else
         With shpPic
            .LockAspectRatio = msoTrue
            If .Width > Columns(colNum).Width Then .Width = Columns(colNum).Width
            Rows(rwNum).RowHeight = .Height
         End With
      End If
   End If

End Sub
 
Back
Top