Looking to Import 2 Most Recent Files in Excel

phredryxun96

New Member
Joined
Jul 1, 2019
Messages
1
I am looking to have some code to import the 2 most recent files in a folder. With the way my code is currently set up it writes every filepath in the folder. I am looking to only write the filepaths of the 2 most recent files placed in the folder.

I have placed the code I am looking to modify below.

Thanks


Sub Files()


Worksheets("File Names").Activate
Range("A2:B1000").ClearContents


Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer


'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder("G:\myfilepath")
i = 1
'loops through each file in the directory and prints their names and path




For Each objFile In objFolder.Files
'print file name

If Right(objFile.Name, 3) = "txt" Then
If objFile.Size > 0 Then

Cells(i + 1, 1) = objFile.Name
'print file path
Cells(i + 1, 2) = objFile.Path
Cells(i + 1, 3) = objFile.DateLastModified
i = i + 1
End If


End If

Next objFile


Application.Run ("Import")


Worksheets("Controls").Activate


End Sub
 

Excel Facts

What is the last column in Excel?
Excel columns run from A to Z, AA to AZ, AAA to XFD. The last column is XFD.

Forum statistics

Threads
1,223,948
Messages
6,175,565
Members
452,652
Latest member
eduedu

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top