There actually is a way to do this by using WMI
and executing queries on CIM_DataFile
. The subroutine below would recursively query each subfolder and gather files based on the CreationDate
property.
Sub WMIGetFile()
Dim strComputer As String
Dim strDateFrom As String
Dim strDateTo As String
Dim fso, f, subf, oWMI, colFiles, cf
strComputer = "."
strDateFrom = "20180101000000.000000+00" ' 01/01/2018
strDateTo = "20191231000000.000000+00" ' 12/31/2019
Set oWMI = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.getFolder("C:\FolderName\")
For Each subf In f.SubFolders
Debug.Print subf.Path
Set colFiles = oWMI.ExecQuery( _
"SELECT * FROM CIM_DataFile" & _
" WHERE Drive = 'C:' AND Path = '\\" & Replace(Right(subf.Path, Len(subf.Path) - 3), "\", "\\") & "\\'" & _
" AND CreationDate >= '" & strDateFrom & "'" & _
" AND CreationDate <= '" & strDateTo & "'")
For Each cf In colFiles
Debug.Print cf.Name
Next cf
Set colFiles = Nothing
Next subf
End Sub
Path
is formatted with \\
instead of \
as a path delimiter starting from the drive specified in Drive
, hence the Replace(Right())
method.
Also worth noting that WMI dates are formatted as strings by yyyymmddhhmmss.000000
.
EDIT:
My brain missed the part where you need to execute this on the main folder as well. In that case, I'd just define it as a function and pass the parameters like this
Sub WMIGetFile()
Dim fso, f, subf, oWMI
Dim strComputer As String
strComputer = "."
Set oWMI = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.getFolder("C:\FolderName\")
QueryCIMDATAFILE oWMI, f
For Each subf In f.SubFolders
QueryCIMDATAFILE oWMI, subf
Next subf
End Sub
Function QueryCIMDATAFILE(conn, path)
Dim colFiles, cf
Dim strDateFrom As String
Dim strDateTo As String
strDateFrom = "20180101000000.000000+00" ' 01/01/2018
strDateTo = "20191231000000.000000+00" ' 12/31/2019
Set colFiles = conn.ExecQuery( _
"SELECT * FROM CIM_DataFile" & _
" WHERE Drive = 'C:' AND Path = '\\" & Replace(Right(path.path, Len(path.path) - 3), "\", "\\") & "\\'" & _
" AND CreationDate >= '" & strDateFrom & "'" & _
" AND CreationDate <= '" & strDateTo & "'")
For Each cf In colFiles
Debug.Print cf.Name
Next cf
Set colFiles = Nothing
End Function