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
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