繁体   English   中英

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

[英]Pull data from most recent file in folder

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

我的问题是我的主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

我建议如下所示,因为您正在使用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

暂无
暂无

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

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