How to traverse files (conditionally) faster than using FileSystemObject - excel

I've written some VBA code using file objects to go into a folder, search for particular files (CSV) that meet certain criteria (contain "HR" in filename and created within specified date range), and copy/paste information out of that file into a master file. The master file is typically a compilation of 250+ workbooks.
The macro works as it should, but it takes about 12 minutes to run, which is a bit excessive. I believe it takes so long to run because it is indexing a folder with 30,000+ files in it.
I've copied the relevant lines of my code below, if anyone is aware of any modifications I could make that would decrease the duration of my macro, I would really appreciate it. I'm relatively new to VBA and coding in general, so I'm learning as I go with these sorts of things! Thanks!
Dim FilePath As String
Dim FileName As String
Dim objFSO As FileSystemObject
Dim objFolder As Folder
Dim objFile As file
Dim fileDate As Date
Dim firstDate As Date
Dim secondDate As Date
'Defining the user-input variables
Worksheets("Sheet1").Activate
firstDate = Cells(2, "E").Value
secondDate = Cells(3, "E").Value
'FilePath to information, defining file objects
FilePath = "\\SRV-1\process\DUMP\"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(FilePath)
'Going through Dump folder and finding high resolution files created within the date range
For Each objFile In objFolder.Files
'Checking to see if the file contains the string "HR", indicating high resolution.
If InStr(1, objFile.Name, "HR") Then GoTo Line1 Else GoTo Line3
Line1:
'Storing the file as a variable and checking its creation date
FileName = objFile.Name
OpenFile = FilePath & FileName
fileDate = FileDateTime(OpenFile)
'Checking to see if the file was created between the user input master roll start/end dates
If firstDate < fileDate And secondDate > fileDate Then GoTo Line2 Else GoTo Line3
Line2:
Do stuff: open dump workbook, copy/pase certain range into main workbook, close dump workbook, next objFile
Line3:
Next objFile

This ought to show some improvement, considering the ratio of HR files to total files (250 / 30,000).
Using Dir Function, Minimize reliance on FileSystemObject
The idea here is to use the Dir function first to get a list of all file names that contain the "HR" substring, and only use the FileSystemObject against those files to get the timestamp information -- there's no use incurring the overhead of FSO on every file in that directory.
Then, we process only those files which match the "HR" criteria:
Sub usingDir()
Dim folderPath As String
Dim fileName As String
Dim filesToProcess As New Collection
Dim item As Variant
Dim fileDate As Date
Dim firstDate As Date
Dim secondDate As Date
'Defining the user-input variables
firstDate = Cells(2, "E").Value
secondDate = Cells(3, "E").Value
folderPath = "\\SRV-1\process\DUMP\"
' Gets a collection of files matching the "HR" criteria
fileName = Dir(folderPath)
Do While Not fileName = ""
If InStr(fileName, "HR") > 0 Then
'Only processing files with "HR"
filesToProcess.Add (folderPath & fileName)
End If
fileName = Dir
Loop
'Now we deal only with the "HR" files:
With CreateObject("Scripting.FileSystemObject")
For Each item In filesToProcess
' Check the date last modified
fileDate = .GetFile(item).DateLastModified ' modify as needed
If firstDate < fileDate And secondDate > fileDate Then
'
'
Debug.Print item
'your code to Do Stuff goes here
'
'
'
End If
Next
End With
End Sub
UPDATE: Without Using the FileSystemObject
This was nagging at me, and I figured there must be a way to get the timestamp information without relying on FileSystemObject. There is. We'll still use Dir to traverse the files, but now we'll eliminate any reference to FileSystemObject and replace with some fancy WinAPI function calls. Check out Chip Pearson's article here and download the .bas modules. You'll need the following two files imported to your VBProject:
modGetSetFileTimes
modTimeConversionFunctions
And then you can do something like this:
Option Explicit
Sub withoutFSO()
Dim folderPath As String
Dim FileName As String
Dim filesToProcess As New Collection
Dim item As Variant
Dim fileDate As Date
Dim firstDate As Date
Dim secondDate As Date
'Defining the user-input variables
firstDate = Cells(2, "E").Value
secondDate = Cells(3, "E").Value
folderPath = "\\Your\Path"
' Gets a collection of files matching the "HR" criteria and our Date range
FileName = Dir(folderPath)
Do While Not FileName = ""
'Only processing files with "HR"
If InStr(FileName, "HR") > 0 Then
' Only process files that meet our date criteria
fileDate = CDate(modGetSetFileTimes.GetFileDateTime(CStr(item), FileDateLastModified))
If firstDate < fileDate And secondDate > fileDate Then
filesToProcess.Add (folderPath & FileName)
End If
End If
FileName = Dir
Loop
'Now we deal only with the matching files:
For Each item In filesToProcess
Debug.Print item
Debug.Print fileDate
'your code to Do Stuff goes here
'
'
'
Next
End Sub
This should be an improvement even over my original answer, and, if combined with a more efficient manner of retrieving data (i.e., using ADO instead of Workbooks.Open, if possible) then you should be very optimized.

Take a look at Power Query -- it's a Microsoft add-in for Excel versions 2012 & 2013, and built-in to 2016. Setting up PQ to do this will be amazingly fast, and the 'script' is reusable! No VBA needed.
You can search and combine the multiple files on the specified criteria, but then merge or append to the new/master file, too. For efficiency, rather than processing each file individually, might I suggest gathering up all the data files (by your criteria), combining them to one table, then use the new table to merge/append to the new/master
Hope this helps...

In addition to using the Dir function instead of FileSystemObject, if you cannot automate PowerQuery, and all you need is the data and not the formatting, consider making a direct data connection to the source workbooks using ADODB.
Add a reference to Microsoft ActiveX Data Objects 6.1 Library (via Tools -> References...). There may be versions other than 6.1; choose the highest.
Then you can use something like the following code:
Dim fso As New Scripting.FileSystemObject
Dim filepath As Variant
For Each filepath In filesToProcess
' Check the date last modified
fileDate = fso.GetFile(item).DateLastModified ' modify as needed
If firstDate < fileDate And secondDate > fileDate Then
Dim connectionString As String
connectionString = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=""" & filepath & """;" & _
"Extended Properties=""Excel 12.0;HDR=No"""
Dim worksheetName As String
worksheetName = "Sheet1"
' There can be multiple worksheets per workbook.
' If you are only interested in one worksheet per workbook, then fill in worksheetName somehow
' Otherwise, you will probably need an inner loop to iterate over all the worksheets
Dim sql As String
sql = _
"SELECT * " & _
"FROM [" & worksheetName & "$]"
Dim rs As New ADODB.Recordset
rs.Open sql, connectionString
destinationWorksheet.Range("A1").CopyFromRecordset rs
rs.Close
Set rs = Nothing
End If
Next

It took a long time because for each interation you pass the information to the main worksheet.
In this case is better use a multidimensional array to keep the information and in the end of the process you pass the the array info in the main worksheet.
I dont know what information you get in each worksheet, soo i cant create an didatical example for you.

Related

VBA for-loop over specific files and confirm date

I have three workbooks (Book1,Book2,Book3) all saved as xlsx files. Each day, these workbooks are updated. Assume all workbooks belong to the following directory: C:\Users\abc\Documents\Example which also contains many other files (d,e,f.... etc). I need to check that Book1,Book2,Book3 are updated so that 'Date Modified' = Today's date. If date modified does not equal today's date i need the code to stop running and warn "Incorrect Date". I imagine this task will involve running a for-loop but I am quite new to VBA.
Try:
Sub test()
Dim arrFileNames As Variant
Dim i As Long
Dim strPath As String
Dim strExt As String
arrFileNames = Split("Book1,Book2,Book3", ",")
strPath = "C:\Users\marios.p\Desktop\test" & "\"
strExt = ".xlsx"
Set fs = CreateObject("Scripting.FileSystemObject")
For i = LBound(arrFileNames) To UBound(arrFileNames)
Set f = fs.GetFile(strPath & arrFileNames(i) & strExt)
If f.DateLastModified < Date Then
MsgBox "Incorrect Date"
End If
Next i
End Sub

VBA - Find Specific Sub Folders by Name Identifiers

The heading may need to be adjusted as it might come across as a duplicate question.
I do apologize for the long winded question.
With the help of these links:
https://www.ozgrid.com/forum/forum/help-forums/excel-general/83263-search-for-file-with-wildcards-and-partial-filename
VBA macro that search for file in multiple subfolders
VBA search for a specific subfolder in many folders and move all the files in it
I have the code below:
Public Sub grab_Folder_Name()
Dim todayDate As String, yesterdayDate As String, folderTime As String, startTime As String, endTime As String
Dim basePath As String, fileName As String
Dim parentFolder As Folder, subFolder1 As Folder, subFolder2 As Folder
Dim myDateArray As Variant
Dim fsoFileSystem As New FileSystemObject
Dim tmpltWkbk As Workbook
Dim kwArray As Variant, sTime As Variant, eTime As Variant
Dim ws1 As Worksheet
Dim i As Long, r As Range
'Set dates to look between
todayDate = Format(DateAdd("d", 0, Date), "dd_mm_YYYY")
yesterdayDate = Format(DateAdd("d", -1, Date), "dd_mm_YYYY")
'Set workbook to work with
Set tmpltWkbk = Workbooks("Template.xlsm")
'Set sheet to work with
Set ws1 = tmpltWkbk.Sheets("Run Results")
'Set default time structure in variable
folderTime = "##.##.##"
'Set date array
myDateArray = Array(todayDate, yesterdayDate)
'Set time Array for Start Time
sTime = Array("18:00:00", "00:00:00")
'Set time Array for End Time
eTime = Array("11:59:00", "06:00:00")
'Get the range to use
Set rng = find_Header("KW ID", "Array")
'Print out array values
'Just for my debugging
ReDim arr(1 To rng.count)
i = 1
For Each r In rng
arr(i) = r.Value
i = i + 1
Next r
kwArray = arr
For i = LBound(kwArray) To UBound(kwArray)
Debug.Print kwArray(i)
Next
'Get the path of the parent folder
basePath = "\\path"
'Set the parent folder
Set parentFolder = fsoFileSystem.GetFolder(basePath)
'Check if the path contains a \ at the end, if not then add it
If Right(basePath, 1) <> "\" Then basePath = basePath & "\"
'Set the directory in a variable
fileName = Dir(basePath, vbDirectory)
'Looop through all the KW
For Each kwID In kwArray
'Loop through all the dates
For Each myDate In myDateArray
'Loop through all the first set of subfolders
For Each subFolder1 In parentFolder.SubFolders
Debug.Print subFolder1.Name
Debug.Print myDate
If subFolder1.Name Like Not "########_##-##-##_##.##.##" Then
'Don't know what to do - Do nothing?
Else
'********** This never seems to be a match **********
'Check if the subFolder1 matches the format
If subFolder1.Name = "########_" & myDate & "_" & folderTime Then
If myDate = todayDate Then
startTime = sTime(1)
endTime = eTime(1)
ElseIf myDate = yesterdayDate Then
startTime = sTime(2)
endTime = eTime(2)
End If
'Check if the subFolder1 is between the times specified
If subFolder1.DateCreated > startTime And subFolder1.DateCreated < endTime Then
'Loop through all the second set of subfolders
For Each subFolder2 In subFolder1.SubFolders
'Check if the subFolder2 matches the format
If subFolder2.Name = "#########_" & kwID & "_" & folderTime Then
With ws1
'.Hyperlinks.Add Anchor:=.Cells.Find(what:=kwID)
'Grab the hyperlink
'Address:=subFolder1.path
'.FollowHyperlink subFolder1.path
'Nothing happens here - The If Condition is not met
Debug.Print subFolder1.Name
End With
End If
Next subFolder2
End If
End If
End If
'This one prints all the folder names in this folder
Debug.Print subFolder1.Name
Next subFolder1
Next myDate
Next kwID
End Sub
Here is a breakdown of what it is I require and what I still need to do:
Create an array of KW ID numbers from a range in the data sheet
Navigate to a folder path for the base folder
Loop through each of the sub-folders looking for the folder name structure that will be: MachineName_Date_Time --> Date(YYYY/MM/DD), Time(HH:MM:SS)
The only dates that are relevant are today and the previous day
The only times that are relevant are Today(00:00:01 --> 06:30:00), Yesterday(18:00:00 --> 00:00:00)
If a folder is found matching the above structure, then I need to go into that folder and loop through those sub folders looking for another folder name structure
The second folder name will be: MachineName_KWID_Time
With this folder name, the only relevant thing is the KWID, which needs to be match for one of the KW ID's stored in the array
The code I am providing so goes up until step 8 - I don't have anything for step 9 - 12 as of yet
If a match is found, I need to then enter that folder and look at the files within
The only file I am looking for, is an image file with PNG extension
If there is an image file in the folder, I need to grab the name of the image file and place that name in a cell in my workbook alongside the KWID value
Once all of this is done, I need to create a hyperlink to this folder - the folder that contains the image - and set the hyperlink to the KWID cell in my workbook
Here are my issues I am experiencing:
The first sub-folder always seems to be MachineName_12-03-2019_08.20.42. There are folders after and before this one, but this one is ALWAYS first
While looping through the folders, it will find dates newer than 12-03-2019, but it does not seem to be searching from latest created date downwards
The myDate variable returns today's date - 15/03/2019 - So I know this is finding the correct date
I'm not sure what validation I should do to check if the the sub-folder name matches the "format" required. There may be a file or folder in the directory that do not match the required folder name format
Because I am unable to move past this if statement: If subFolder1.Name = "########_" & myDate & "_" & folderTime Then, I cannot test what is happening after it
I have commented out the code for grabbing the hyperlink as I am not sure if it is correct and I get an error on this line .Hyperlinks.Add Anchor:=.Cells.Find(what:=kwID)
Argument not optional
If I am able to work through the issues I am experiencing, then I could continue working on the rest of my task and add to the code.

Is it possible to create a path to Excelfiles with VBA?

I am building a report on Excel that has to be updated monthly. Therefore I get every month a new Excelfile with data that has to be summarized in the report.
The report consists of the calculations of the specific Excelfiles with the data for each month, for example the amount of male or female customers.
Is it possible to create a macro via VBA that creates a path to the new Excelfile so that I do not have to change the path to the file manually? In this case for example instead that I have to change the formula to '...non_activated-2019-03' by typing it in, Excel should do it automatically because there are over 60 of these calculations in which I would have to change the file.
=COUNTIFS('C:\Users\denni\Desktop\Reporting\Non Activated\[non_activated-2019-02.xlsx]non_activated-2019-02'!$M:$M;$B$9;'C:\Users\denni\Desktop\Reporting\Non Activated\[non_activated-2019-02.xlsx]non_activated-2019-02'!$B:$B;$C10)
Yes, it is possible and I do it myself when I need to create reports and log files. Just add the following in your filename String:
filename = "...non_activated-" & Year(Date) & "-" & Month(Date)
Month Number with 0
If you want the month number to start with 0, you can simply change the code like this:
Sub yourSub()
'...
filename = "...non_activated-" & Year(Date) & "-" & getMonthNumber(Date)
'...
End Sub
Function getMonthNumber(data As Date) As String
If Month(data) < 10 Then
getMonthNumber = "0" & Month(data)
Else
getMonthNumber = Month(data)
End If
End Function
Open your file
There're a lot of ways to open (and write on) your file. You can try this:
Open yourPath & yourFilename For Output As #1
Print #1, "Print somenthing on your file"
'Do your stuff
Close #1
Now you have your file saved on your path.
Notes
By using this method, every month it creates automatically a new file which you can easily find.
Just remember to check if the file exists, otherwise it can launch
an exception.
You could use a function like so in a cell, on a sheet, then reference the cell in formulas, then leave them alone.
For example =GetLatestImportFile("C:\workspace\dummy data\")
Function GetLatestImportFile(strPath As String, _
Optional strLookFor As String = "non-activated")
Dim f As Scripting.FileSystemObject
Dim fld As Scripting.Folder
Dim fl As Scripting.File
Dim dt As Date
Set f = New Scripting.FileSystemObject
Set fld = f.GetFolder(strPath)
For Each fl In fld.Files
If InStr(1, fl.Name, strLookFor) > 0 Then
If fl.DateCreated > dt Then
dt = fl.DateCreated
GetLatestImportFile = fl.Name
End If
End If
Next fl
set f=nothing
set fld=nothing
set fl=nothing
End Function
So for now this code is doing quite well and replaces the old reference with the new one!
Sub MySub()
Dim old as String
Dim new as String
Dim i as Integer
old = "activated-2019-01"
new = "activated-2019-02"
For i=4 to 160
Cells(i,"E").FormulaLocal = Replace(Cells(i,"F").FormulaLocal, old, new)
Next i
End Sub

Excel VBA: Copy data from multiple passwordprotected workbooks in a folder into one worksheet in another workboo

I have written a code that opens a password protected workbook in a folder, copy some values out of it and paste the values in active woorkbook. This works fine.
My problem is that I have 16 password protected files in this folder, and I need a loop that does the same thing with every file. Below you can find the code, and I think all my problems should be properly explained with comments inside the code. Please ask if anything is unclear. In advance, thanks for any help!
Code:
Sub Bengt()
Dim sPath As String
Dim vFolder As Variant
Dim sFile As String
Dim sDataRange As String
Dim mydata As String
Dim wb As Workbook
Dim WBookOther As Workbook
Dim myArray As Variant '<<does the list of passwords have to be array?
sPath = ThisWorkbook.Path & Application.PathSeparator
sDataRange = "Budsjett_resultat'!E2" '<<every file I want to open has data in this sheet and range
sFile = "BENGT.xlsm" '<< how to make sFile be every file in folder?
' here I want a loop that opens every woorkbook in the folder M::\SALG\2016\Budsjett\
Set WBookOther = Workbooks.Open(sPath & sFile, Password:="bengt123")
' all passwords starts with filename + three numbers after as you can see
' here I want to make excel find the password out of a list of passwords in range B100:B116
mydata = "='" & sPath & "[" & sFile & "]" & sDataRange
'mydata = "='M:\SALG\2016\Budsjett\Bengt.xlsmBudsjett_resultat'!E2:E54" '<< change as required
'link to worksheet
With ThisWorkbook.Worksheets(1).Range("T2:T54")
'in this case I want the loop to find "BENGT"(which is the filename) in cell T1, and paste the values in range T2:T54.
'For the other files, I want the loop to find the filename (of the file it opened) in row 1,
'and paste the values in range ?2-?54 at the column with the same name as the filename
.Formula = mydata
.Value = .Value
WBookOther.Close SaveChanges:=False
End With
End Sub
For the password array I have tried following code:
Sub passord()
Dim myArray As Variant
myArray = ThisWorkbook.Worksheets(1).Range("B100:B116")
On Error Resume Next 'turn error reporting off
For i = LBound(myArray, 1) To UBound(myArray, 1)
Set wb = Workbooks.Open("M:\SALG\2016\Budsjett\BENGT.xlsm", Password:=myArray(i, 1))
If Not wb Is Nothing Then bOpen = True: Exit For
Next i
End Sub
I have tried to implement the last sub into the first sub, but I can't figure out how to make it work.

FSO Not Getting Any Files

I'm trying to have the program to copy the files with certain characters. The files to be copied over should be between the today's date and 100 days before today. My program can run, but nothing show up on the new folder. I did make sure that the file is between those date. I don't get any error, so I have no idea where to fix. I have tried other methods, none of them working.
I try to mix the code from http://www.rondebruin.nl/win/s3/win026.htm. I was playing abround with it, only copy_folder() is working. I'm getting runtime error '53' - File not found on Copy_Certain_Files_In_Folder() and Copy_Files_Dates() give me nothing as well.
Anyway, what is wrong with my code and how can I incorporate the FileExt to my code below? Thanks!
Sub CopyPasteFiles()
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
Dim Fdate As Date
Dim FileExt As String
Dim objFile As Object
Dim objFolder As Object
FromPath = "C:\Users\Run" '<< Change
ToPath = "C:\Users\Test" '<< Change
FileExt = "*BT.csv"
If Right(FromPath, 1) <> "\" Then
FromPath = FromPath & "\"
End If
Set FSO = CreateObject("scripting.filesystemobject")
If FSO.FolderExists(FromPath) = False Then
MsgBox FromPath & " doesn't exist"
Exit Sub
End If
If FSO.FolderExists(ToPath) = False Then
MsgBox ToPath & " doesn't exist"
Exit Sub
End If
For Each objFolder In FSO.GetFolder(FromPath).SubFolders
For Each objFile In objFolder.Files
Fdate = Int(objFile.DateCreated)
If Fdate >= Date And Fdate <= Format(DateAdd("d", -100, Date), "dd mmmm yyyy") Then
objFile.Copy ToPath
End If
Next objFile
Next objFolder
MsgBox "You can find the files from " & FromPath & " in " & ToPath
End Sub
Okay, I tried to add some comments to give you some direction.
The first problem you had, is you weren't doing anything with the root folder - you were trying to go right into the subfolders, which is probably why you said it "highlighted" the lines on the outer loop layer. (The highlighted line is the line that will be executed when you hit F8 next.)
What I did was break the copy action into another procedure so you can call it recursively on any subfolders. It's just one way to do it - there are other, probably simpler ways, but it's what came to mind for me as I'm kind of used to digging in folders and recordsets recursively this way.
Another problem you had was your method of comparing dates. The format of the .DateCreated property comes in with date and time. You can directly compare this to the Now() function, which returns date and time - but if you try to compare to the Date() function it won't work because it's a different format.
I wasn't sure what you were trying to do with the file extension bit. I assumed you wanted to use it as a filter, so that's what I did with it.
A few notes:
You currently are telling the user at the end that "you can find the files from " but you are not checking if that is true. You may want to add a check after the .Copy action and then add your results to an array or something so you can show the user a list of files that successfully copied and files that did not. When I was testing, I created the folders you had in my Users directory, and I got an error when trying to copy of not having the required permissions.
Right now the From path, To path, and extension filter are all hard-coded. If you plan to distribute this or will be using it yourself in multiple locations, you could use the BrowseForFolder method to present the user with a folder browser dialog and allow them to select the From and To folders. You could also use InputBox to get a filter from the user. Just a thought.
Anyways, here is what I did with your code. I changed the variable names to my naming convention simply because that is what I'm used to - you can change them however you want.
Option Explicit
Public Sub CopyPasteFiles()
'Declare variables
Dim SRfso As Scripting.FileSystemObject
Dim strFrom As String
Dim strTO As String
Dim strExtFilter As String
Dim SRfolderA As Scripting.Folder
Dim SRfolderB As Scripting.Folder
'Are you always going to hardcode these or do you want to be able to browse for a folder?
strFrom = "C:\Users\Run" '<< Change
strTO = "C:\Users\Test" '<< Change
'I'm not sure what your intent is with this - I assumed you wanted to filter by file extension.
strExtFilter = "*BT.CSV"
'Prep the folder path
If Right(strFrom, 1) <> "\" Then
strFrom = strFrom & "\"
End If
'Intialize the FileSystemObject
Set SRfso = New Scripting.FileSystemObject
'Verify input and output folders exist. Inform user if they don't.
If SRfso.FolderExists(strFrom) = False Then
MsgBox strFrom & " doesn't exist"
Exit Sub
End If
If SRfso.FolderExists(strTO) = False Then
MsgBox strTO & " doesn't exist"
Exit Sub
End If
'Get the input folder using the FileSystemObject
Set SRfolderA = SRfso.GetFolder(strFrom)
'Call the routine that copies the files
MoveTheFiles SRfolderIN:=SRfolderA, strFolderOUT:=strTO ', strExtFilter:=strExtFilter
'Inform the user where they can find the files. CAUTION: You may be misinforming the user.
MsgBox "You can find the files from " & strFrom & " in " & strTO
End Sub
Private Sub MoveTheFiles(ByRef SRfolderIN As Scripting.Folder, _
ByRef strFolderOUT As String, _
Optional ByRef strExtFilter As String = "*.*", _
Optional ByRef blnSUBFOLDERS As Boolean = True)
'This routine copies the files. It requires two arguments. First, it requires the root folder as folder object from the scripting library. _
Second, it requires the output path as a string. There are two optional arguments. The first allows you _
to use a text filter as a string. The second is a boolean that tells us whether or not to move files in subfolders - the default is true.
'Delcare variables
Dim SRfileA As Scripting.File
Dim SRfolderCol As Scripting.Folders
Dim SRfolderA As Scripting.Folder
Dim datCreated As Date
Dim lngFX As Long
Dim blnResult As Boolean
'Find the file extension in the filter
lngFX = InStrRev(strExtFilter, ".", , vbTextCompare)
'Move the files from the root folder
For Each SRfileA In SRfolderIN.Files
'Only work with files that contain the filter criteria
If Ucase(Mid(SRfileA.Name, InStrRev(SRfileA.Name, ".", , vbTextCompare) - (Len(strExtFilter) - lngFX) + 1, Len(strExtFilter))) Like Ucase(strExtFilter) Then
'Only work with files that were created within the last 100 days
datCreated = SRfileA.DateCreated
If datCreated <= Now And (datCreated >= DateAdd("d", -100, Now())) Then
SRfileA.Copy strFolderOUT
End If
End If
Next
'Check if the calling procedure indicated we are supposed to move subfolder files as well
If blnSUBFOLDERS Then
'Check that we have subfolders to work with
Set SRfolderCol = SRfolderIN.SubFolders
If SRfolderCol.Count > 0 Then
For Each SRfolderA In SRfolderIN.SubFolders
MoveTheFiles SRfolderIN:=SRfolderA, strFolderOUT:=strFolderOUT, strExtFilter:=strExtFilter, blnSUBFOLDERS:=blnSUBFOLDERS
Next
End If
End If
End Sub

Resources