简体   繁体   中英

vba open the most recent file in a folder

There are some exel files in a Folder. The aim is to search for the file with the highest date (in the Format: Fundings " & Format(LMD, "DDMMYY") & ".xls) and open it. Eg the file names are Fundings 270818, Fundings 110618 and the most recent would be the first one. The code below runs into the error that the "MyFile = Dir(MyPath, vbNormal)" is empty.

 Dim MyPath  As String
 Dim MyFile  As String
 Dim LatestFile  As String
 Dim LatestDate  As Date
 Dim LMD  As Date

 LMD = Date

 'Specify the path to the folder
 MyPath = "C:\Users\topal\Desktop\Spreaddeterminierung\Fundings " & Format(LMD, "DDMMYY") & ".xls"



 'Get the first Excel file from the folder
 MyFile = Dir(MyPath, vbNormal)

 'If no files were found, exit the sub
 If Len(MyFile) = 0 Then
     MsgBox "No Sir", vbExclamation
     Exit Sub
 End If

 'Loop through each Excel file in the folder
 Do While Len(MyFile) > 0

     'Assign the date/time of the current file to a variable
     LMD = Date

     'If the date/time of the current file is greater than the latest
     'recorded date, assign its filename and date/time to variables
     If LMD > LatestDate Then
         LatestFile = MyFile
         LatestDate = LMD
     End If

     'Get the next Excel file from the folder
     MyFile = Dir

 Loop

 'Open the latest file
 Workbooks.Open MyPath

 End Sub

You could loop the folder and extract the date part of the string and store the greatest value for use to identify the file. The following also applied a file mask of "xlsx" which you can remove or change. It uses a regex to find qualifying filenames according to your stated pattern.

Option Explicit

Public Sub GetLastestDateFile()
    Dim FileSys As Object, objFile As Object, myFolder As Object, strFile As String, dteFile As Long
    Const myDir As String = "C:\Users\User\Desktop\TestFolder"
    Set FileSys = CreateObject("Scripting.FileSystemObject")
    Set myFolder = FileSys.GetFolder(myDir)

    Dim fileName As String, tempDate As Long, fileMask As String

    dteFile = 0: fileMask = "xlsx"
    For Each objFile In myFolder.Files
        If FileSys.GetExtensionName(objFile.Path) = fileMask And ValidateFile(Split(objFile.Name, ".xlsx")(0)) Then
            tempDate = GetDateFromFileName(objFile.Name)
            Dim pseudoDate As String
            pseudoDate = ReArrange(tempDate)
            If pseudoDate > dteFile Then dteFile = pseudoDate
        End If
    Next objFile
    If Not tempDate = 0 Then Workbooks.Open (myDir & "\" & "Fundings " & Format$(ReArrange(dteFile), "000000") & "." & fileMask)
End Sub

Public Function ReArrange(ByVal tempDate As String) As String
    tempDate = Format$(tempDate, "000000")
    ReArrange = Format$(Right$(tempDate, 2), "00") & Format$(Mid$(tempDate, 3, 2), "00") & Format$(Left$(tempDate, 2), "00")
End Function

Public Function ValidateFile(ByVal fileName As String) As Boolean
    With CreateObject("VBScript.RegExp")
        .Global = True
        .MultiLine = True
        .Pattern = "Fundings\s\d{6}$"
        ValidateFile = .test(fileName)
    End With
End Function

Public Function GetDateFromFileName(ByVal fileName As String) As Date
    On Error GoTo errhand
    GetDateFromFileName = Split(Split(fileName, "Fundings ")(1), ".")(0)
    Exit Function
errhand:
    GetDateFromFileName = 0
End Function

Regex:

Try the regex here .

Explanation:

Fundings\s\d{6}$
/
gm

Fundings matches the characters Fundings literally (case sensitive)

\\s matches any whitespace character (equal to [\\r\\n\\t\\f\\v ] )

\\d{6} matches a digit (equal to [0-9] )

{6} Quantifier — Matches exactly 6 times

$ asserts position at the end of a line

Your loop from:

'Loop through each Excel file in the folder Do While Len(MyFile) > 0

  'Assign the date/time of the current file to a variable LMD = Date 'If the date/time of the current file is greater than the latest 'recorded date, assign its filename and date/time to variables If LMD > LatestDate Then LatestFile = MyFile LatestDate = LMD End If 'Get the next Excel file from the folder MyFile = Dir 

This one is doesn't do anything thats why you getting empty values or no action.

I reccomend to totaly change you point of think and try to implement something like this:

vba search through a folder and select files by name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM