如何在Excel 2010中使用VBA获取目录中最后修改的文件

问题描述 投票:0回答:2

我正在寻找一种使用 VBA 在 Excel 2010 中执行此操作的方法。

以前可以在 Excel 2003 中使用 Application.FileSearch 方法,但该方法已被弃用。 (见下文)

Dim sFileName As String

sFileName = ""
With Application.FileSearch
    .NewSearch
    .LookIn = sDir
    .Filename = "*.*"
    .Execute msoSortByLastModified, msoSortOrderDescending

    If .FoundFiles.Count > 0 Then sFileName = .FoundFiles(1)

End With

有什么想法如何在 Excel 2010 中执行此操作吗?

谢谢

excel vba excel-2010 file-search
2个回答
7
投票

如果可以使用 FileSystemObject,则可以使用此处描述的方法。

总结一下:

Dim fso As Scripting.FileSystemObject
Dim fol As Scripting.Folder
Dim fdr As Scripting.Folder
Dim fil As Scripting.File
Dim flc As Scripting.Folders

Set fso = CreateObject("Scripting.FileSystemObject")
Set fol = fso.GetFolder("YourPathName")
Set flc = fol.SubFolders

For Each fdr In flc
  For Each fil In fdr.Files
        Debug.Print fil.DateLastModified
  Next fil
Next fdr

Set fso = Nothing
Set fol = Nothing
Set flc = Nothing

0
投票

Muito bom ajudou aqui,mas de fato este 子文件夹,não ajudou em nada 和 não pegava 或 último arquivo criado 和 sim 或 último 插入意大利面。继续科里吉多。

Sub UltimoArquivo()
    Dim fso As Scripting.FileSystemObject
    Dim fol As Scripting.Folder
    Dim fil As Scripting.File
    Dim StrUltimoDownload As String
    Dim LastDate As Date

StrCaminho = ThisWorkbook.Path

Set fso = CreateObject("Scripting.FileSystemObject")
Set fol = fso.GetFolder(StrCaminho)
LastDate = 0
    For Each fil In fol.Files
        Debug.Print fil.Name; " & - & "; fil.DateLastModified
        If (fil.DateLastModified > LastDate) Or (LastDate = 0) Then
            StrUltimoDownload = fil.Name
            LastDate = fil.DateLastModified
            Debug.Print "Último arquivo: "; fil.Name; " & - & "; fil.DateLastModified
        End If
    Next fil

    Set fso = Nothing
    Set fol = Nothing
    Set flc = Nothing
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.