KlausW
Active Member
- Joined
- Sep 9, 2020
- Messages
- 453
- Office Version
- 2016
- Platform
- Windows
Hi
I have a challenge. I use this VBA code to find the image names in a folder. And import the images. It works really well. The problem is that it shifts the last image one cell down in relation to the image name.
Any help will be appreciated.
Best regards
Klaus W
I have a challenge. I use this VBA code to find the image names in a folder. And import the images. It works really well. The problem is that it shifts the last image one cell down in relation to the image name.
Any help will be appreciated.
Best regards
Klaus W
VBA Code:
Sub Rektangelafrundedehjørner2_Klik()
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 = "D:\Billeder f-div grej\" '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("Ark1")
On Error Resume Next
With ws
.Range("A1") = "Navn"
.Range("B1") = "Billede"
'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