繁体   English   中英

循环查找文件夹中具有特定名称的最后修改文件

[英]Loop find last modified file with a specific name inside a folder

这是我的问题,在我的 excel 表上,我放置了我要检查的每个文件夹的路径

V:\Folder1\
V:\Folder2\

在这些文件夹中,我希望 vba 根据特定名称给我最后修改文件的名称。

我举个例子:

在我的文件夹1中,我有这些文件:

Lo_2021_1
Lo_Full_2021_1
Lo_2021_2
Lo_Full_2021_2
...
Lo_2021_50
Lo_Full_2021_50

在我的文件夹 2 中,我有这些文件:

Li_2021_1
Li_Full_2021_1
Li_2021_2
Li_Full_2021_2
...
Li_2021_50
Li_Full_2021_50

我希望 vba 给我最后修改文件的名称,该文件以我的文件夹 1 中的 Lo_2021 和我的文件夹 2 中的Lo_2021 Li_Full (所以我不想要Lo_FullLi_2021

我已经创建了一个代码,它给了我最后修改文件的名称,但它们是Lo_Full_2021_50Li_Full_2021_50而我想要Lo_2021_50Li_2021_50

这是我的代码:

Option Explicit

Sub name_last_file()

Dim FileSys As FileSystemObject
Dim objFile As File
Dim myFolder
Dim strFilename As String
Dim dteFile As Date
Dim list_path As Range
Dim path_ As Range
Dim myDir As String

Set list_path = Range("B2", Range("B2").End(xlDown))


For Each path_ In list_path
    myDir = path_.Value
    
   'set up filesys objects
    Set FileSys = New FileSystemObject
    Set myFolder = FileSys.GetFolder(myDir)
    
    'loop through each file and get date last modified. If largest date then store Filename
    dteFile = DateSerial(1900, 1, 1)
    
    For Each objFile In myFolder.Files
        If objFile.DateLastModified > dteFile Then
            dteFile = objFile.DateLastModified
            strFilename = objFile.Name
            
    End If
    Next objFile
    MsgBox strFilename
    
Next path_

End Sub

这会给我Lo_Full_2021_50Li_Full_2021_50而我想要Lo_2021_50Li_2021_50

有没有办法说我想要最后一个以Lo_2021Li_2020开头的修改文件,以便我得到Lo_2021_50Li_2021_50作为结果?

我真的很感谢你的帮助

请测试下一个更新的代码:

Sub Give_name_files()
 Dim FileSys As FileSystemObject, objFile As File, myFolder As oobject
 Dim strFilename As String, dteFile As Date, list_path As Range, path_ As Range
 Dim strRoot As String

 strRoot = "Lo_2021" 'the beginning of the tested files name

 'First I Select paths that are on my excel cells
 Set list_path = Range("B2", Range("B2").End(xlDown))

 For Each path_ In list_path
    myDir = path_.Value

    'Set up filesys objects
    Set FileSys = New FileSystemObject
    Set myFolder = FileSys.GetFolder(myDir)

    'loop through each file and get date last modified. If largest date then store Filename
    dteFile = DateSerial(1900, 1, 1)

    For Each objFile In myFolder.Files
        If left(objFile.Name, Len(strRoot)) = strRoot Then
            If objFile.DateLastModified > dteFile Then
               dteFile = objFile.DateLastModified
               strFilename = objFile.Name
            End If
        End If
    Next objFile
    MsgBox strFilename
 Next path_
End Sub

暂无
暂无

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

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