Excel VBA Macro: Open Newest File (In User Selected Folder)

preview_player
Показать описание
Excel VBA Macro: Open Newest File (In User Selected Folder). In this video, we go over how to automatically find and open the latest file in a user selected folder.

Code (YouTube doesn't allow brackets; so LT and GT are used for less than and greater than, respectively):

Sub newest_file_in_folder()

Dim FldrPicker As FileDialog
Dim myPath As String
Dim myFile As String
Dim newestFile As String
Dim newestDate As Date

Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

With FldrPicker
.Title = "Please Select Folder"
.AllowMultiSelect = False
.ButtonName = "Confirm"
If .Show = -1 Then
myPath = .SelectedItems(1) & "\"
Else
End
End If
End With

myFile = Dir(myPath)
newestFile = myFile

On Error GoTo noFiles
newestDate = FileDateTime(myPath & myFile)

Do While myFile LTGT ""

If FileDateTime(myPath & myFile) GT newestDate Then
newestFile = myFile
newestDate = FileDateTime(myPath & myFile)
End If

myFile = Dir

Loop

Workbooks.Open Filename:=myPath & newestFile
End

noFiles:

MsgBox "There are no items in this folder."

End Sub

#ExcelVBA #ExcelMacro
Рекомендации по теме
Комментарии
Автор

I'm completely new to macros and trying to work on one for work. I have it created (based off simple recording/following my movements in excel) and edited basic things in VBA. However I need some help...every day we hit the button and it's supposed to go grab a weather file, the name of this file changes daily with the date...I have no idea where or how I'm supposed to enter what you're saying here off my information I already had in there....or how it knows where to go with just the mypath myfile my folder ☹️

suziedkingery
Автор

If I need to select any other folder apart from Documents Folder, how can I define the Path? right now with program default Docs folder is opening from C drive

gopalsriharsha