VBA: цикл по файловой системе и поиск самого нового файла - PullRequest
1 голос
/ 25 марта 2019

В моей программе я хочу просмотреть сложную файловую структуру и отобразить в ней самый новый файл.

Файловая структура имеет несколько папок и подпапок, в большинстве случаев пустых. Таким образом, этот макрос поможет определить, где находится последняя информация.

Sub newestFile()
Dim FileSystem as object
Dim MostRecentFile as string
Dim MostRecentDate as Date
Dim FileSpec as String
Dim filename as string

'This is where i specify what type of files i would be looking for
FileSpec ="*.*"

'This is where i specify where the master directory is, so that i may look down into it
Directory ="c:\Directory1\"
filename = Dir(Directory & FileSpec)

set Filesystem = CreateObject("Scripting.FileSystemObject")
Do Folder FileSystem.getFolder(Directory)

set ws = Sheets("Events")
ws.cells(2,7).value = MostRecentFile
ws.cells(2,8).value = MostRecentDate
end sub

private Function DoFolder(Directory)

For each subfolder in Directory.SubFolders
   DoFolder subfolder

Dim file

For each File in Directory.files
    'actions go here
    If File <> "" Then
    MostRecentFile = File
    MostRecentDate = FileDateTime(Directory)
        If FileDateTime(File) > MostRecentDate Then
            MostRecentFile = File
            MostRecentDate = FileDateTime(File)
        End if
    End If
next

next

End Function

в этом коде я всегда теряю переменные (MostRecentFile и MostRecentDate), когда код переходит в другую подпапку.

Я ожидал, что у меня будет имя самого нового файла (всей структуры) и дата.

Ответы [ 2 ]

1 голос
/ 25 марта 2019

Как уже было сказано, сфера, безусловно, вызывает беспокойство.Вот цикл внутри подпрограммы:

Sub newestFile()
    Dim FileSystem As Object  ' Needed to get file properties
    Set FileSystem = CreateObject("Scripting.FileSystemObject")
    Dim MostRecentDate As Date
    Dim MostRecentFile As String
    Directory = "c:\Directory1\"
    FileSpec = "*.txt"                  '<-- can be "*.xls*" or whatever criteria needed
    MyFile = ""
'Loop through text files in Directory finding the most current file
    MyFile = Dir(Directory & FileSpec)  'Get first file name in directory
    Do While MyFile <> ""
        If MostRecentDate < FileSystem.GetFile(Directory & MyFile).DateLastModified Then
            MostRecentDate = FileSystem.GetFile(Directory & MyFile).DateLastModified
            MostRecentFile = MyFile
        End If
        MyFile = Dir                    'Get next file matching criteria
    Loop
    set ws = Sheets("Events")
    ws.cells(2,7).value = MostRecentFile
    ws.cells(2,8).value = MostRecentDate
End Sub
1 голос
/ 25 марта 2019

Вам необходимо объявить переменные на уровне модуля

Private MostRecentFile as string
Private MostRecentDate as Date

Sub newestFile()
....
End Sub
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...