Hello, in reference to the code from user @yky (Using VBA to pull images from folder to sheet) im using the following the code for inserting pictures automatically from a folder into a worksheet:
My problem is that i am getting the error message "An error occured while importing this file: C:\Users\me\Desktop". I changed the folder name to my specific picture location and figured out that changing the .Addpictures parameter SaveWithDocument:=False to SaveWithDocument:=True makes the error disappear, but then also nothing happens. I'm not an deep expert in VBA and maybe someone on this forum can quickly overlook and solve this situation. I would really appreciate your help . Thank you!
VBA Code:
Sub insert_pictures()
Const factor = 0.9 'picture is 90% of the size of cell
'Variable Declaration
Dim fsoLibrary As FileSystemObject
Dim fsoFolder As Object
Dim sFolderPath As String
Dim sFileName As Object
Dim p As Object
Dim i As Long 'counter
Dim last_row As Long
Dim ws As Worksheet
sFolderPath = "C:\Users\me\Desktop" 'may need to change this line to suit your situation
'Set all the references to the FSO Library
Set fsoLibrary = CreateObject("Scripting.FileSystemObject")
Set fsoFolder = fsoLibrary.GetFolder(sFolderPath)
Set ws = ThisWorkbook.Sheets("Sheet1")
On Error Resume Next
With ws
.Range("A1") = "Name"
.Range("B1") = "Picture"
'Loop through each file in a folder
i = 2
For Each sFileName In fsoFolder.Files
.Cells(i, 1) = Left(sFileName.Name, InStr(sFileName.Name, ".") - 1)
i = i + 1
' Debug.Print sFileName.Name
Next sFileName
last_row = i
Range(.Cells(2, 1), .Cells(i, 1)).Sort key1:=.Cells(2, 1), order1:=xlDescending
For i = 2 To last_row Step 1
Set p = .Shapes.AddPicture(Filename:=sFolderPath _
& Cells(i, 1).Value & ".jpg", LinkToFile:=False, SaveWithDocument:=True, _
Left:=.Cells(i, 2).Left, Top:=Cells(i, 2).Top, Width:=-1, Height:=-1)
p.Width = .Cells(i, 2).Width * factor
'adjust row height
If .Cells(i, 2).RowHeight < p.Height / factor Then
.Cells(i, 2).RowHeight = p.Height / factor
End If
p.Left = .Cells(i, 2).Left + (.Cells(i, 2).Width - p.Width) / 2
p.Top = .Cells(i, 2).Top + (.Cells(i, 2).Height - p.Height) / 2
Next i
End With
'Release the memory
Set fsoLibrary = Nothing
Set fsoFolder = Nothing
End Sub
My problem is that i am getting the error message "An error occured while importing this file: C:\Users\me\Desktop". I changed the folder name to my specific picture location and figured out that changing the .Addpictures parameter SaveWithDocument:=False to SaveWithDocument:=True makes the error disappear, but then also nothing happens. I'm not an deep expert in VBA and maybe someone on this forum can quickly overlook and solve this situation. I would really appreciate your help . Thank you!