Searching a folder to match each file to a table - vba

I added a For loop (see k part) and it really slows down my entire program. Is it possible make this more efficient?
I am searching a specific folder and trying to match each file to a table in my spreadsheet. I am trying to make Quarters(1,j) in the For k loop same as Quarters(i,j) from the lower part of the code but not sure how to do that since I have already used integer i.
For j = 1 To 2
For k = 1 To 39
If k <= 29 Then
'Looks at all the files in the folder for the given Quarter
SourceFolderName = FolderPath & "\" & Quarters(1, j)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(SourceFolderName)
End If
If k > 29 Then
SourceFolderName = FolderPath & "\" & Quarters(k, j)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(SourceFolderName)
End If
For Each objFile In objFolder.Files
i = 1
NotAssigned = True
'Keep going until we match the file
While NotAssigned = True
'If the beginning of the file name matches for a given state,
'assign the file name to that state for this quarter
If Left(objFile.Name, 9) = StateAbbr(i, 1) & Quarters(i, j) & "FA" Then
WBName(i, j) = objFile.Name
'Stop trying to match the file
NotAssigned = False
End If
If i = 39 Then NotAssigned = False
i = i + 1
Wend
Next objFile
Set objFile = Nothing
Set objFolder = Nothing
Set objFSO = Nothing
Next k
Next j

I managed to change my entire code to use DIR instead of looping each cell in spreadsheet and looping each file in my folder. My run time cut down from 40 min to 2 second!!!!!!! I am so amazed by this now. Here is the solution if you are interested.
Dim StrFile As String
For j = 1 To 2
For i = 1 To 39
StrFile = Dir(FolderPath & "\" & Quarters(i, j) & "\*FA*")
Do While Len(StrFile) > 0
If Left(StrFile, 9) = StateAbbr(i, 1) & Quarters(i, j) & "FA" Then
WBName(i, j) = StrFile
End If
StrFile = Dir
Loop
Next i
Next j

Related

Output in a different workbook

I've created a tool and the below macro copies all .csv files into a excel sheet. I want the data to be copied to the "Consol.xlsx" file that I created. The current code copies the data in the tool not the "Consol.xlsx" file. I am unable to update the code so that the data gets copied correctly.
Below is my code:
Sub Button_click2()
Call AddNew
Call ImportCSVsWithReference
End Sub
Sub AddNew()
Application.DisplayAlerts = False
Dim thisWb As Workbook
Set thisWb = ActiveWorkbook
Workbooks.Add
ActiveWorkbook.SaveAs Filename:=thisWb.path & "\Consol.xlsx"
Application.DisplayAlerts = True
End Sub
Sub ImportCSV()
Dim strSourcePath As String
Dim strDestPath As String
Dim strFile As String
Dim strData As String
Dim x As Variant
Dim Cnt As Long
Dim r As Long
Dim c As Long
Application.ScreenUpdating = False
'Change the path to the source folder accordingly
strSourcePath = Application.ActiveWorkbook.path
If Right(strSourcePath, 1) <> "\" Then strSourcePath = strSourcePath & "\"
'Change the path to the destination folder accordingly
strDestPath = Application.ActiveWorkbook.path
If Right(strDestPath, 1) <> "\" Then strDestPath = strDestPath & "\"
strFile = Dir(strSourcePath & "*.csv")
Do While Len(strFile) > 0
Cnt = Cnt + 1
r = Cells(Rows.count, "A").End(xlUp).Row + 1
Open strSourcePath & strFile For Input As #1
Do Until EOF(1)
Line Input #1, strData
x = Split(strData, ",")
For c = 0 To UBound(x)
Cells(r, c + 1).Value = Trim(x(c))
Next c
r = r + 1
Loop
Close #1
Name strSourcePath & strFile As strDestPath & strFile
strFile = Dir
Loop
Application.ScreenUpdating = True
If Cnt = 0 Then _
MsgBox "No CSV files were found...", vbExclamation
End Sub
Well it looks like you've got both of the pieces there. Your first subroutine saves a blank workbook called consol.xlsx.
Then, your second subroutine loops through the directory, opens each csv file, and copes it to some unspecified range.
What I would insert before your loop is:
Set wbkConsol = Workbooks.Open(thisWorkbook.path & "\Consol.xlsx")
Then, during your loop over the CSV files:
strFile = Dir(strSourcePath & "*.csv")
Do While Len(strFile) > 0
Cnt = Cnt + 1
r = Cells(Rows.count, "A").End(xlUp).Row + 1
Open strSourcePath & strFile For Input As #1
Do Until EOF(1)
Line Input #1, strData
' Set wshAdd = wbkConsol.Worksheets.Add() ' New ws in wbk
' wshAdd.Name = left(strFile, 31) ' First 31-chars of filename.
x = Split(strData, ",")
For c = 0 To UBound(x)
wshAdd.Cells(r, c + 1).Value = Trim(x(c))
Next c
r = r + 1
Loop
Close #1
Name strSourcePath & strFile As strDestPath & strFile
strFile = Dir()
Loop
As an added note: you could pass your workbook from your first sub to the second sub, by reference. That way, you won't have to open it up again. This would be by combining the button click into just a single command.
Sub1()
wbkConsol = workbooks.Add
Call sub2(wbkConsol)
End sub

Code to include longer file name where the file name is a number

I am trying to edit code that someone else wrote. I have done NO VBA and very little coding in general.
The original code is written for a 5 digit number and we now have files that are six digits. I have tried to copy the code but change it to 6 digit numbers below the current code above Next objFile at the end. This has not worked.
The main issue here is I didn't write the original code and I don't understand the logic. I have tried just changing all of the 5's to 6's and the 99999 to 999999. I have tried copying from Folder = "" down, changing them to 6 digits and pasting below Next objFile. This didn't work either.
Sub CopyPics()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim varDirectory As Variant
Dim objSubFolder As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(Application.ActiveWorkbook.Path)
Dim Dest As String
Dest = "R:\Field Assurance\FA PHOTOS AND INFORMATION\"
'Loop through each file in this folder
For Each objFile In objFolder.Files
Folder = "" 'Empty old folder name
MainFolder = "" 'Empty old folder name
For i = 1 To Len(objFile.Name)
Test = Mid(objFile.Name, i, 5)
If Test >= 10000 And Test <= 99999 Then 'For files: Find any five numbers in a row and assume it to be the file number.
Folder = "NC-" & Mid(objFile.Name, i, 5) 'If found, create new folder.
i = Len(objFile.Name) 'In other words, take the first 5 numbers, then get out.
End If
Next
For Each objSubFolder In objFolder.subfolders 'Find the main folder.
If Right(Folder, 5) >= Mid(objSubFolder.Name, 4, 5) And Right(Folder, 5) <= Mid(objSubFolder.Name, 18, 5) Then 'If my file number is within the main folder bounds...
MainFolder = objSubFolder.Name & "\" 'Use that folder.
End If
Next objSubFolder
If Len(Folder) = 8 And Len(MainFolder) = 23 Then 'If real folders are identified...
On Error Resume Next
If Dir(Dest & MainFolder & Folder) = "" Then 'Check to see if the directory/folder does not exist...
objFSO.CreateFolder (Dest & MainFolder & Folder) 'If not, make one.
End If
'Rename that file's directory to be the new one - aka cut and paste file into new folder.
Name Application.ActiveWorkbook.Path & "\" & objFile.Name As Dest & MainFolder & Folder & "\" & objFile.Name
End If
Next objFile
ActiveWorkbook.Close
End Sub
This is a bit more complex than your original code but I think it's more robust...
Lightly tested.
Option Explicit
Sub CopyPics()
'use constants for fixed values
Const DEST As String = "R:\Field Assurance\FA PHOTOS AND INFORMATION\"
Dim objFSO As Object, srcFolder As Object, objFile As Object
Dim objSubFolder As Object, destFolder As Object, fNum, folderName, picFolderName
Dim FileWasMoved As Boolean, sMsg
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set srcFolder = objFSO.GetFolder(Application.ActiveWorkbook.Path) 'ThisWorkbook.Path ?
Set destFolder = objFSO.GetFolder(DEST) 'parent destination folder
'Loop through each file in this folder
For Each objFile In srcFolder.Files
FileWasMoved = False 'reset "moved" flag
fNum = ExtractNumber(objFile.Name) 'get the file number
If Len(fNum) > 0 Then 'any number found?
folderName = "NC-" & fNum
For Each objSubFolder In destFolder.subfolders 'Find the subfolder.
If IsTheCorrectFolder(objSubFolder.Name, fNum) Then
picFolderName = objSubFolder.Path & "\" & folderName
If Not objFSO.folderexists(picFolderName) Then
objFSO.CreateFolder picFolderName
End If
'move the file
Name objFile.Path As picFolderName & "\" & objFile.Name
FileWasMoved = True 'flag file as moved
Exit For
End If
Next objSubFolder
End If 'filename contains a number
'if file was not moved then add it to the list....
If Not FileWasMoved Then sMsg = sMsg & vbLf & objFile.Name
Next objFile
'warn user if some files were not moved
If Len(sMsg) > 0 Then
MsgBox "Some files were not moved:" & vbLf & sMsg, vbExclamation
End If
End Sub
'Return true/false depending on whether this is the correct
' folder to hold the specified filenumber
Function IsTheCorrectFolder(folderName, fileNumber) As Boolean
Dim arr, num1, num2, rv As Boolean
rv = False 'default return value
arr = Split(folderName, "thru") 'split folder name on "thru"
If UBound(arr) = 1 Then 'should have two parts
'get the numbers from each part and compare against the file number
num1 = ExtractNumber(arr(0))
num2 = ExtractNumber(arr(1))
If Len(num1) > 0 And Len(num2) > 0 Then
fileNumber = CLng(fileNumber) 'convenrt to Long for comparison
rv = (fileNumber >= CLng(num1) And fileNumber <= CLng(num2))
End If
End If
IsTheCorrectFolder = rv
End Function
'Extract the first 5- or 6-digit number from a string
' Match is "greedy" so if there are six digits it will match 6 and
' not just the first 5...
Function ExtractNumber(txt)
Dim re As Object, allMatches, rv
Set re = CreateObject("VBScript.RegExp")
re.Pattern = "(\d{5,6})"
re.ignorecase = True
re.Global = True
Set allMatches = re.Execute(txt)
If allMatches.Count > 0 Then rv = allMatches(0) 'if there's a match then return the first one
ExtractNumber = rv
End Function
You need to change the lower limit in IF condition also. Like
If Test >= 10000 And Test <= 99999 Then
becomes
If Test >= 100000 And Test <= 999999 Then
Currently the loop could be exiting when it finds the first five digit number.

Deleting all files except few

So I have to write a script to delete all files except n newest (most recently created). I'm running my script with two arguments: folder directory and number of files that shouldn't be removed.
Here is my script, but it is actually removing random files. How can I make it to leave n newest files?
How I run script: delete C:\users\Adam\Desktop\Test 3
My script:
Dim address
Dim n
Set fso = CreateObject("Scripting.FileSystemObject")
If (Wscript.Arguments.Count <> 2) Then
MsgBox("Wrong number of paramets")
Else
address = Wscript.Arguments(0)
n = Wscript.Arguments(1)
MsgBox( address & " " & n)
Set objFolder = fso.GetFolder(address)
For Each objFile in objFolder.files
If n <> 0 Then
n = n - 1
else
objFile.Delete True
End If
Next
End if
Code with sort:
Function SortFiles(files)
ReDim sorted(files.Count - 1)
Dim file, i, j
i = 0
For Each file in files
Set sorted(i) = file
i = i + 1
Next
For i = 0 to files.Count - 2
For j = i + 1 to files.Count - 1
If sorted(i).DateLastModified < sorted(j).DateLastModified Then
Dim tmp
Set tmp = sorted(i)
Set sorted(i) = sorted(j)
Set sorted(j) = tmp
End If
Next
Next
SortFiles = sorted
End Function
If (Wscript.Arguments.Count <> 2) Then
MsgBox("Wrong number of paramets")
else
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Dim files
address = Wscript.Arguments(0)
n = Wscript.Arguments(1)
Set files = fso.GetFolder(address).Files
Dim file
For Each file in SortFiles(files)
If n <> 0 Then
n = n - 1
else
file.Delete True
End If
Next
end if
The following should do the job:
Dim address
Dim n, no_of_files
Set fso = CreateObject("Scripting.FileSystemObject")
If (Wscript.Arguments.Count <> 2) Then
MsgBox("Wrong number of paramets")
Else
address = Wscript.Arguments(0)
n = Wscript.Arguments(1)
MsgBox( address & " " & n)
Set objFol = fso.GetFolder(path)
no_of_files = n
While no_of_files>0
latestDate = 0
Set objFiles = objFol.Files
'Loop to get the creation date of the newest File
For Each file In objFiles
tempDate = file.DateCreated
If CDate(tempDate)>CDate(latestDate) Then
latestDate = tempDate
End If
Next
'Loop to delete the newest file using the date fetched in the last loop
For Each file In objFiles
If file.DateCreated = latestDate Then
file.Delete True
End If
Next
no_of_files = no_of_files-1
Wend
End if
Set fso = Nothing

Read a CSV file and list of folders and then compare in VB

What I am trying to achieve is I currently have a (main) folder filled with many Sub-folders and these sometimes get drag & dropped into another Sub-folder by accident.
I have an CSV file containing all the names of the current (main) folder list as it should stand and I want to check this against the current version of Sub-folders found in the (main) folder and output a message box with the results of matching files and missing files.
This is the code I have got so far although I am unsure how to check the list of folders against the CSV file.
Read data from an CSV file.
'Holds Data from CSV file
Dim arrValue As String()
'create a new TextFieldParser and opens the file
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\Users\USERNAME\Dropbox (Personal)\IT\jobs.csv")
'Define the TextField type and delimiter
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
While Not MyReader.EndOfData
Dim arrCurrentRow As String() = MyReader.ReadFields()
If arrValue Is Nothing Then
ReDim Preserve arrValue(0)
arrValue(0) = arrCurrentRow(0)
Else
ReDim Preserve arrValue(arrValue.Length)
arrValue((arrValue.Length - 1)) = arrCurrentRow(0)
End If
End While
Read list of folders
'check against the Clients folder
Set w = WScript.CreateObject("WScript.Shell")
w.Popup ShowFolders("C:\Users\USERNAME\Dropbox (Innovation PS)\Clients")
Function ShowFolders(folderName)
'Setting Variables
Dim fs, f, f1, fc, s
'holds folder name
s = ""
'Obtain folder Object
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFolder(folderName)
'Obtain SubFolders collection within folder
Set fc = f.SubFolders
'Examine each item in the collection
For Each f1 in fc
s = s & f1.name
s = s & (Chr(13) & Chr(10)) ' Chr(13) & Chr(10) = Carriage return–linefeed combination
Next
ShowFolders = s
End Function
'See if it matches the .CSV file
Thank you in advance. (Also if you could include comments it would be appreciated)
Run this script to get a base line, it wil create a spreadsheet of the folders files and properties, Then runt it again copy the sheet in to the baseline work bbok and do a vlookup. You could also use this as a base line to create a csv and compare the it that way. Not exactly waht you are looking for but it is a workable solution
Const ForReading = 1, ForWriting = 2, Forappending = 8
'Option Explicit
'DIM Objects
'Dim variabbles
Dim folderspec
'Dim
DIM arrBlk(3)
DIM arrFLN(3)
DIM arrInfo(3)
Set objXL = Wscript.CreateObject("Excel.Application")
Set ofso = CreateObject("Scripting.FileSystemObject")
folderspec = InputBox("Please enter the path", "FileList", " ")
If folderspec = "" Then
' if cancel is selected quit the program
wscript.quit
ElseIf folderspec = " " Then
' if nothing is entered give a warning message ang quit the program
msgbox "No Directory has been seleted " & vbCrLf
wscript.quit
End If
intRow = 2
buildsheet() 'Build the XLS spreadsheet
'folderspec ="C:\_epas_5.0\Web_Server\ASP"
'folderspec ="C:\_epas_5.0\Web_Server\COM+ Source"
strFldrCmp = folderspec
Set root = ofso.GetFolder(folderspec)
ShowFileList(root)
For Each oFolder in root.subfolders
walkfolder oFolder
Next
Sub walkfolder(f)
ShowFileList(f)
For Each sf in f.subfolders
walkfolder sf
Next
End Sub
Function ShowFileList(folderspec)
Dim oFolder
Dim oFiles
Dim oFile
Set oFolder = ofso.GetFolder(folderspec)
' Wscript.echo oFolder.name
Set oFiles = oFolder.Files
' If IsEmpty(oFiles) Then Wscript.echo oFolder.name
'i = 0
For Each oFile in oFiles
i = 1 + i
'If i < 1 Then
'Wscript.echo oFolder.name,i
'End If
Next
If i < 1 Then
Wscript.echo oFolder.name & " Null"
ReDim arrB(3)
'strPath = Replace(oFolder.path,strFldrCmp,"", 1 ,1 ,vbTextCompare)
arrB(0) = "\" & Trim(oFolder.Name) 'oFolder.path
arrB(1) = ""
arrB(2) = ""
arrB(3) = ""
AddLineToXLS(arrB)
End If
For Each oFile in oFiles
ReDim arrB(3)
srtfldr = oFolder.path
' MsgBox srtfldr& " " & strFldrCmp
'strPath = Replace(srtfldr,strFldrCmp,"", 1 ,1 ,vbTextCompare)
strPath = Replace(oFolder.path,strFldrCmp,"", 1 ,1 ,vbTextCompare)
'strPath = Replace("C:\_5Test\Web_Server\ASP\app\admin","C:\_5Test\Web_Server\ASP","",,,vbTestCompare)
arrB(0) = Trim(strPath) 'oFolder.path
arrB(1) = Trim(oFile.name)
arrB(2) = Trim(oFile.Size)
arrB(3) = Trim(oFile.DateLastModified)
If LCase(ofso.GetExtensionName(oFile)) <> "scc" Then 'skip VSS .scc files
AddLineToXLS(arrB)
End If
Next
End Function
Function buildsheet
intRow = 1
objXL.Visible = True
objXL.WorkBooks.Add
'** Set Row Height
objXL.Rows(1).RowHeight = 17
'** Set Column widths
objXL.Columns(1).ColumnWidth = 40.14
objXL.Columns(2).ColumnWidth = 33.14
objXL.Columns(3).ColumnWidth = 15
objXL.Columns(4).ColumnWidth = 23
objXL.Columns(5).ColumnWidth = 23
objXL.Columns(6).ColumnWidth = 23
'** Set Cell Format for Column Titles ***
objXL.Range("A1:F1").Select
objXL.Selection.Font.Bold = True
' objXL.Selection.Font.Size = 8
objXL.Selection.Interior.ColorIndex = 15
objXL.Selection.Interior.Pattern = 1 'xlSolid
objXL.Selection.Font.ColorIndex = 1
objXL.Selection.WrapText = True
objXL.Columns("A:T").Select
objXL.Columns.Font.Size = 8
objXL.Selection.HorizontalAlignment = 1 'xlCenter
objXL.Columns("C:C").Select
objXL.Selection.NumberFormat = "#,###0"
objXL.Columns("D:D").Select
objXL.Selection.NumberFormat = "m/d/yy h:mm AM/PM"
'*** Set Column Titles ***
Dim arrA(3)
arrA(0)= "File Path"
arrA(1) = "File Name"
arrA(2) = "Size(bytes)"
arrA(3) = "Modified Date/Time"
AddLineToXLS(arrA)
End Function
Function AddLineToXLS(r)' Writes a line to the spreadsheet recieves an array as input
objXL.Cells(intRow, 1).Value = r(0)
objXL.Cells(intRow, 2).Value = r(1)
objXL.Cells(intRow, 3).Value = r(2)
objXL.Cells(intRow, 4).Value = r(3)
' MsgBox r(3)
'objXL.Cells(intRow, 5).Value = r(4)
'objXL.Cells(intRow, 6).Value = r(5)
' objXL.Cells(intRow, 4).Value = r(3)
intRow = intRow + 1
objXL.Cells(1, 1).Select
End Function

Excel VBA - PDF file properties

first-time poster but long-time fan for finding VBA and SQL solutions on this site. I have a VBA subroutine that is designed to find all PDF files within a directory that the user designates. The program does recursions through all subfolders and generates a spreadsheet as follows:
Column A: complete file path ("C:\Users\Records\NumberOne.pdf")
Column B: folder path containing the file ("C:\Users\Records\")
Column C: the file name itself ("NumberOne.pdf")
Up to this point, the program (code below) works flawlessly. I've used it to search a directory with over 50,000 PDF files, and it successfully generates the spreadsheet every time (total elapsed time for the program is usually 5-10 minutes in large directories).
The problem is that I want to add Column D to capture the date that the PDF file was created. I have Googled this and labored over it for hours, trying techniques like FSO.DateCreated and so forth, and nothing has worked. If FSO.DateCreated is what I need, I'm not sure where to insert it in my subroutine to make it work. Usually I get an error that the object does not support that property or method. Does anybody happen to know where I can insert the proper code for my program to find the date each PDF was created and drop it into Column D on my output spreadsheet?
Sub GetFiles()
'-- RUNS AN UNLIMITED RECURSION SEARCH THROUGH A TARGETED FOLDER AND FINDS ALL PDF FILES WITHIN
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim j As Long
Dim ThisEntry As String
Dim strDir As String
Dim FSO As Object
Dim strFolder As String
Dim strName As String
Dim DateCreated As Date '--(Possibly String?)
Dim strArr(1 To 1048576, 1 To 1) As String, i As Long
Dim fldr As FileDialog
'-- OPEN DIALOG BOX TO SELECT DIRECTORY THE USER WISHES TO SEARCH
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select the directory you wish to search"
.AllowMultiSelect = False
If .Show <> -1 Then
Exit Sub
Set fldr = Nothing
Else
strDir = .SelectedItems(1) & "\"
End If
End With
'-- LOOK FOR RECORDS WORKSHEET; IF IT DOES NOT EXIST, CREATE IT; IF IT DOES EXIST, CLEAR CONTENTS
If Not (wsExists("records")) Then
Worksheets.Add
With ActiveSheet
.Name = "records"
End With
Set ws = ActiveSheet
Else
Sheets("records").Activate
Range("A1:IV1").EntireColumn.Delete
Set ws = ActiveSheet
End If
'-- SET SEARCH PARAMETERS
Let strName = Dir$(strDir & "\" & "*.pdf")
Do While strName <> vbNullString
Let i = i + 1
Let strArr(i, 1) = strDir & strName
Let strName = Dir$()
Loop
'-- UNLIMITED RECURSIONS THROUGH SUBFOLDERS
Set FSO = CreateObject("Scripting.FileSystemObject")
Call recurseSubFolders(FSO.GetFolder(strDir), strArr(), i)
Set FSO = Nothing
'-- CREATE COLUMN HEADERS ON OUTPUT WORKSHEET
With ws
Range("A1").Value = "AbsolutePath"
Range("B1").Value = "FolderPath"
Range("C1").Value = "FileName"
Range("D1").Value = "DateCreated"
End With
If i > 0 Then
ws.Range("A2").Resize(i).Value = strArr
End If
lr = Cells(Rows.Count, 1).End(xlUp).Row
For i = 1 To lr
ThisEntry = Cells(i, 1)
'-- EXTRACT FOLDER PATH AND FILE NAME FROM STRING
For j = Len(ThisEntry) To 1 Step -1
If Mid(ThisEntry, j, 1) = Application.PathSeparator Then
Cells(i, 2) = Left(ThisEntry, j)
Cells(i, 3) = Mid(ThisEntry, j + 1)
Exit For
End If
Next j
Next i
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
----------
Private Sub recurseSubFolders(ByRef Folder As Object, _
ByRef strArr() As String, _
ByRef i As Long)
Dim SubFolder As Object
Dim strName As String
For Each SubFolder In Folder.SubFolders
Let strName = Dir$(SubFolder.Path & "\" & "*.pdf")
Do While strName <> vbNullString
Let i = i + 1
Let strArr(i, 1) = SubFolder.Path & "\" & strName
Let strName = Dir$()
Loop
Call recurseSubFolders(SubFolder, strArr(), i)
Next
End Sub
You need to get the file with GetFile before you can access the DateCreated.
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(myFileName)
str = f.DateCreated
MsgBox (str)
Your code is fine (beside some issues with indentation). I just added the instruction to get the creation date from the file system, as you can see below:
Set FSO = CreateObject("Scripting.FileSystemObject")
For i = 1 To lr
ThisEntry = Cells(i, 1)
'-- EXTRACT FOLDER PATH AND FILE NAME FROM STRING
For j = Len(ThisEntry) To 1 Step -1
If Mid(ThisEntry, j, 1) = Application.PathSeparator Then
Cells(i, 2) = Left(ThisEntry, j)
Cells(i, 3) = Mid(ThisEntry, j + 1)
Cells(i, 4) = FSO.GetFile(ThisEntry).DateCreated
Exit For
End If
Next j
Next i
I don't know why you weren't able to use the FSO object, but I believe it can be because few lines below you set it to nothing, so I instantiated it again before the first For cycle:
Set FSO = CreateObject("Scripting.FileSystemObject")
Hope this helps,
The Macro Guru
FileSystem.FileDateTime(inputfilepath) returns a variant or date of when the file was last created or modified.