How to search keyword based on text files modified date?

215 Views Asked by At

I have multiple text files that are generated everyday.

I would like to search "apple" string from the latest modified text file. If the string is not found, i will need to search from yesterday's text file. If it still not found, i will need to search from day before yesterday's text file. The process keep going until i find the string.

Take an example:

Text file created today named : 08112018.txt
Text file created yesterday named : 08102018.txt
Text file created day before yesterday named : 08192018.txt

I will start my search for "apple" in 08112018.txt first. If it's not found, i will search "apple" in 08102018.txt. The process continues until "apple" is found.

1

There are 1 best solutions below

2
On

Here's what I think will give you the best result:

Start by listing all your files into a disconnected record set:

Set fso = CreateObject("Scripting.FileSystemObject")
Const ForReading = 1  

Set list = CreateObject("ADOR.Recordset")
list.Fields.Append "name", 200, 255
list.Fields.Append "date", 7
list.Open

For Each f In fso.GetFolder("C:\your-folder-location").Files
  list.AddNew
  list("name").Value = f.Path
  list("date").Value = f.DateLastModified
  list.Update
Next

list.MoveFirst

You can then sort those by date last modified:

list.Sort = "date DESC"

Now you can start from the top of the list and work your way through.

Dim foundApple

list.MoveFirst
Do Until list.EOF Or foundApple

    Do Until objTextFile.AtEndOfStream
        Set objTextFile = fso.OpenTextFile(list("name"), ForReading)
        strLine = objTextFile.ReadLine()

        If InStr(strLine, "apple") <> 0 then foundApple = True
    Loop

    ' If foundApple = True Then (Do whatever stuff you need)
    list.MoveNext
Loop

list.Close
  • I've just brain-dumped this code. It's not tested. YMMV.