123rich456,
Welcome to the forum!
Give the below code a try. When you run it, you'll be asked to select the folder containing the JPG files. After that, you'll be asked to select the cell that the picture will be placed in. This is the cell that will have the top-left corner of the image.
Sub Insert_Newest_JPG()
Dim rngDest As Range
Dim FSO As Object
Dim oFile As Object
Dim oPic As Object
Dim dTimeNow As Double
Dim dTimeSince As Double
Dim strFolderPath As String
Dim strFilePath As String
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
If .Show = False Then Exit Sub 'Pressed cancel
strFolderPath = .SelectedItems(1)
End With
dTimeNow = Now
dTimeSince = 1000000
Set FSO = CreateObject("Scripting.FileSystemObject")
For Each oFile In FSO.GetFolder(strFolderPath).Files
If Right(oFile.Name, 4) = ".jpg" Then
If dTimeNow - oFile.DateLastModified < dTimeSince Then
dTimeSince = dTimeNow - oFile.DateLastModified
strFilePath = oFile.Path
End If
End If
Next oFile
If Len(strFilePath) > 0 Then
Set oPic = LoadPicture(strFilePath)
On Error Resume Next
Set rngDest = Application.InputBox("Select the estination cell for the image", "Desination Cell", Type:=8)
On Error GoTo 0
If rngDest Is Nothing Then Exit Sub 'Pressed cancel
Set rngDest = rngDest.Cells(1)
ActiveSheet.Shapes.AddPicture strFilePath, msoFalse, msoTrue, rngDest.Left, rngDest.Top, Round(oPic.Width / 26.458, 0), Round(oPic.Height / 26.458, 0)
Else
MsgBox "No .jpg files found in " & strFolderPath, , "Insert Image Error"
End If
End Sub
How to use a macro:- Make a copy of the workbook the macro will be run on
- Always run new code on a workbook copy, just in case the code doesn't run smoothly
- This is especially true of any code that deletes anything
- In the copied workbook, press ALT+F11 to open the Visual Basic Editor
- Insert | Module
- Copy the provided code and paste into the module
- Close the Visual Basic Editor
- In Excel, press ALT+F8 to bring up the list of available macros to run
- Double-click the desired macro (I named this one Insert_Newest_JPG)
Bookmarks