简体   繁体   English

VBA打开文件夹中的最新文件

[英]vba open the most recent file in a folder

There are some exel files in a Folder. 文件夹中有一些exel文件。 The aim is to search for the file with the highest date (in the Format: Fundings " & Format(LMD, "DDMMYY") & ".xls) and open it. 目的是搜索日期最高的文件(格式:Fundings“&Format(LMD,” DDMMYY“)&” .xls)并打开它。 Eg the file names are Fundings 270818, Fundings 110618 and the most recent would be the first one. 例如,文件名是Fundings 270818,Findings 110618,而最新的名称是第一个。 The code below runs into the error that the "MyFile = Dir(MyPath, vbNormal)" is empty. 下面的代码遇到错误,即“ MyFile = Dir(MyPath,vbNormal)”为空。

 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. 下面还应用了可以删除或更改的文件掩码"xlsx" 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) Fundings与字面上的Fundings完全匹配(区分大小写)

\\s matches any whitespace character (equal to [\\r\\n\\t\\f\\v ] ) \\s匹配任何空格字符(等于[\\r\\n\\t\\f\\v ]

\\d{6} matches a digit (equal to [0-9] ) \\d{6}匹配一个数字(等于[0-9]

{6} Quantifier — Matches exactly 6 times {6}量词-精确匹配6次

$ asserts position at the end of a line $在行尾声明位置

Your loop from: 您的循环来自:

'Loop through each Excel file in the folder Do While Len(MyFile) > 0 '遍历文件夹中的每个Excel文件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 VBA搜索文件夹并按名称选择文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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