在我的程序中,我想浏览一个复杂的文件结构,并在其中显示最新的文件。
文件结构有几个文件夹和子文件夹,大多数情况下为空。因此,该宏有助于揭示最新信息的位置。
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)。
我希望拥有(整个结构的)最新文件的名称和日期。
答案 0 :(得分:1)
您需要在模块级别声明变量
Private MostRecentFile as string
Private MostRecentDate as Date
Sub newestFile()
....
End Sub
答案 1 :(得分:1)
DataAvailable