从文件夹中的最新文件中提取数据

时间:2019-06-27 17:52:45

标签: excel vba

尝试使用文件夹中的最新文件存储数据。

我的问题是我的主excel文件不会使用最新数据文件(xlsx)中的数据来提取数据。我的代码当前具有当前文件的名称(例如"Network-2019.xlsm"),但可以说我插入了一个名为“ network.xlsm”的文件,该文件稍后发布在文件夹中。我希望主数据集能够识别并导入数据。

Function GetMostRecentExcelFile(ByVal myDirectory As String, ByVal filePattern As String) As String

    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")

    Dim myFolder As Object
    Set myFolder = fso.getfolder(IIf(Right(myDirectory, 1) = "\", myDirectory, myDirectory & "\"))

    Dim currentDate As Date
    Dim fname As String

    Dim currentFile As Object
    For Each currentFile In myFolder.Files
        If (currentDate = CDate(0) Or currentFile.DateCreated > currentDate) And currentFile.name Like filePattern _
            And InStr(LCase$(currentFile.name), ".xlsx") > 0 And InStr(currentFile.name, "~$") = 0 Then

            currentDate = currentFile.DateCreated
            fname = currentFile.name

        End If
    Next currentFile

    GetMostRecentExcelFile = fname

End Function

1 个答案:

答案 0 :(得分:1)

由于您使用的是FileSystemObject

,因此我建议如下所示

请注意,我使用了早期绑定。关联的智能感知功能非常有用,如果出于任何原因您可以随时更改为后期绑定。

Option Explicit
Function GetMostRecentExcelFile(sFolderPath As String) As String
    Dim FSO As FileSystemObject
    Dim FO As Folder, FI As File, recentFI As File

Set FSO = New FileSystemObject
Set FO = FSO.GetFolder(sFolderPath)

For Each FI In FO.Files
    Select Case FI.Name Like "*.xlsx"
        Case True
            Select Case recentFI Is Nothing
                Case True
                    Set recentFI = FI
                Case False
                    If FI.DateCreated > recentFI.DateCreated Then
                        Set recentFI = FI
                    End If
            End Select
    End Select
Next FI

GetMostRecentExcelFile = recentFI.Path
End Function