How to search keyword based on text files modified date? - string

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.

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.

Related

How to get file name text from attachment in PR in SAP

I want to get the file name from an attachment inside a Purchase Requisition in SAP using VBA.
I have tried already changing the last line for some random numbers bu nothing happened and I can't manage to discover where I can get the file name.
session.findByid("wnd[0]/usr/subSUB0:SAPLMEGUI:0010/subSUB2:SAPLMEVIEWS:1100/subSUB2:SAPLMEVIEWS:1200/subSUB1:SAPLMEGUI:3212/cntlGRIDCONTROL/shellcont/shell").pressToolbarButton "&MEREQDMS"
'here my code tells me if there are any attachment in purchase requisition item
doc = session.findByid("wnd[1]/usr/tblSAPLCVOBTCTRL_DOKUMENTE/ctxtDRAW-DOKNR[1,0]").Text
'starts on item line (0)
n = 0
Do While doc <> ""
session.findByid("wnd[1]/usr/tblSAPLCVOBTCTRL_DOKUMENTE/ctxtDRAW-DOKNR[1," & n & "]").SetFocus
session.findByid("wnd[1]/usr/tblSAPLCVOBTCTRL_DOKUMENTE/ctxtDRAW-DOKNR[1," & n & "]").caretPosition = 5
'opens the attachment page with the documents inside for download
session.findByid("wnd[1]").sendVKey 2
Application.AutomationSecurity = msoAutomationSecurityForceDisable
Application.AutomationSecurity = msoAutomationSecurityByUI
q = 1
s = 0
'num_files returns me "PDF" or "XLS".
num_files = session.findByid("wnd[0]/usr/tabsTAB_MAIN/tabpTSMAIN/ssubSCR_MAIN:SAPLCV110:0102/cntlCTL_FILES1/shellcont/shell/shellcont[1]/shell").getnodetextbypath(q)
...
Here is the file with file name I need VBA tells me ("Escopo Plataforma..."):
Please try the following.
for example:
...
'num_files returns me "PDF" or "XLS".
num_files = session.findByid("wnd[0]/usr/tabsTAB_MAIN/tabpTSMAIN/ssubSCR_MAIN:SAPLCV110:0102/cntlCTL_FILES1/shellcont/shell/shellcont[1]/shell").getnodetextbypath(q)
myFileName = session.findByid("wnd[0]/usr/tabsTAB_MAIN/tabpTSMAIN/ssubSCR_MAIN:SAPLCV110:0102/cntlCTL_FILES1/shellcont/shell/shellcont[1]/shell").getitemtext(CStr(q),"C 7")
I assume Item Name "C 7" will be different for you. This is how you determine the correct ItemName:
Record a script with the SAP GUI script recorder.
Click with the mouse in the column with the file name.
Leave the cursor there and finish the recording.
Look in the recorded script for the ItemName.
Regards, ScriptMan

cognos impromptu macro for prompt date entry

If I type in a file name to load an *.imr file after my Impromptu catalog is loaded, we have a prompt for a date to be entered. I get a syntax error by doing this way.
Strfilename = ("g:\ filename.imr", "10/15/2014")
The syntax error is generated from Impromptu.
I want to be able to put in the date automatically rather than having to type it.
I haven't programmed Impromptu in over a decade, but I hope this can help you!
Sub passer()
Dim impapp As Object, imprep As Object, cutdate As Variant
On Error GoTo handler
Set impapp = CreateObject("impromptu.application.30")
cutdate = InputBox("Enter date: ")
impapp.Visible 1
impapp.opencatalog "d:\cognos\i66\samples\outdoors.cat", "Creator", "", "", ""
impapp.openreport "d:\cognos\i66\samples\reports\matt.imr", (cutdate)
Set imprep = impapp.activedocument
imprep.exportexcel ("d:\mydocu~1\matt2.xls")
imprep.closereport
Set imprep = Nothing
Set impapp = Nothing
Exit Sub
handler:
MsgBox "Error with " & Error$()
End Sub
The date is a input into a [ prompt ] for the monday for that week. So I load the catalog and the .imr file,,,,,, then you have a prompt that asked for that monday,,, I can generate the Mondays date , and it doesn't matter weather I quote the "date" or value the date I get errors trying to add it to the end of the file name . Just like the way you did it there by adding [ .imr", (date) ]
that doesn't work eather.

Search using VBscript and populate Options dynamically

Objective
To search through a bunch of lines in a text file, and if a match is found populate that line in a Options list that is displayed in HTA.
Eg: If 'Setup' is found in 5 lines out of total 10, all the 5 lines need to be populated as 'Options'
Code
Set objFSO = CreateObject("Scripting.Filesystemobject")
Set objRegEx = New RegExp
With objRegEx
.Pattern = "(\b" & "setup" & "\b)"
.IgnoreCase = True
.Global = True
End With
Set objOpen = objFSO.OpenTextFile ("FileList.lst", 1)
Contents = objOpen.ReadAll
Set objMatchAll = objRegEx.Execute( Contents )
If objMatchAll.count > 0 Then
Set objOpen = objFSO.OpenTextFile ("FileList.lst", 1)
Do Until objOpen.AtEndOfStream
Line = objOpen.ReadLine
Set objMatchAny = objRegEx.Execute( Line )
If objMatchAny.count > 0 Then
Set objOption = Document.createElement("OPTION")
objOption.Text = Line
objOption.Value = Line
ValuesList.add objOption
'Matched = Matched & vbNewLine & Line
MatchCount = MatchCount + 1
End If
Loop
Else
MsgBox "No results"
End If
Explanation
The code looks for the term 'setup' (of course this is dynamically populated at the time of execution) in the file 'FileList.lst'. When results are found an 'Option' object is generated and added to the 'ValuesList' List which is in an HTML body using tags.
Note 1: The reason i generate an 'Options' object instead of just loading the line is so that we can populate the tag. The tag is used so we can select any one of the search result.
Note 2: The reason the 'Contents' variable is created so that incase if there are no matches at all, it need not go to each line to find a match, which would take longer to just display that message.
Problem
The code works fine, tested upto 150 results (outcome), but when there is a large number of matches my HTA freezes.
Question
Can the existing code be modified to perform better, like a different method to instead of creating the an 'Options' object, an alternate method to generate the 'ValuesList' ?
Instead of running two objRegEx search results, is there way to return the matched line from 'Contents' Varialable ?
Update
Ok, i ran my script without the objOption part which is not creating and adding options to my ValuesList, only regexp parsing through 58k lines, also resulting in 58k matches and the outcome was 3secs ... so looks like i need an alternative to populate my HTA options list ... its not able to handle that many options to select from ... any alternatives ? I used the same logic in a browser and the entire browser freezes ...
It seems like you really only care about whether or not the regex matches in a particular line or not. Since you don't need to know how many matches occurred, nor do you need the actual match text, you can use the Test method instead. This should be faster because it will stop after the first match, plus it doesn't have to construct the Matches collection. I'd also leave the Global property at its default value of False for pretty much the same reason, but if you're just using the Test method, I don't think the Global property matters.
Thanks to Cheran Shunmugavel i found out that the best way is to use DocumentFragments. I impleted that concept in my code and the results were great !
New Code
Set objFSO = CreateObject("Scripting.Filesystemobject")
Set objRegEx = New RegExp
With objRegEx
.Pattern = "(\b" & "setup" & "\b)"
.IgnoreCase = True
.Global = True
End With
Set objFragment = Document.createDocumentFragment()
Set objOpen = objFSO.OpenTextFile ("FileList.lst", 1)
Contents = objOpen.ReadAll
Set objMatchAll = objRegEx.Execute( Contents )
If objMatchAll.count > 0 Then
Set objOpen = objFSO.OpenTextFile ("FileList.lst", 1)
Do Until objOpen.AtEndOfStream
Line = objOpen.ReadLine
Set objMatchAny = objRegEx.Execute( Line )
If objMatchAny.count > 0 Then
Set objOption = Document.createElement("OPTION")
objOption.innerHTML = Line
objFragment.appendchild objOption
MatchCount = MatchCount + 1
End If
Loop
ViewList.appendChild objFragment.cloneNode(True)
Else
MsgBox "No results"
End If
Old Code : 53mins 23secs
New Code : 31secs

Extract tables from pdf (to excel), pref. w/ vba

I am trying to extract tables from pdf files with vba and export them to excel. If everything works out the way it should, it should go all automatic. The problem is that the table are not standardized.
This is what I have so far.
VBA (Excel) runs XPDF, and converts all .pdf files found in current folder to a text file.
VBA (Excel) reads through each text file line by line.
And the code:
With New Scripting.FileSystemObject
With .OpenTextFile(strFileName, 1, False, 0)
If Not .AtEndOfStream Then .SkipLine
Do Until .AtEndOfStream
//do something
Loop
End With
End With
This all works great. But now I am getting to the issue of extracting the tables from the text files.
What I am trying to do is VBA to find a string e.g. "Year's Income", and then output the data, after it, into columns. (Until the table ends.)
The first part is not very difficult (find a certain string), but how would I go about the second part. The text file will look like this Pastebin. The problem is that the text is not standardized. Thus for example some tables have 3-year columns (2010 2011 2012) and some only two (or 1), some tables have more spaces between the columnn, and some do not include certain rows (such as Capital Asset, net).
I was thinking about doing something like this but not sure how to go about it in VBA.
Find user defined string. eg. "Table 1: Years' Return."
a. Next line find years; if there are two we will need three columns in output (titles +, 2x year), if there are three we will need four (titles +, 3x year).. etc
b. Create title column + column for each year.
When reaching end of line, go to next line
a. Read text -> output to column 1.
b. Recognize spaces (Are spaces > 3?) as start of column 2. Read numbers -> output to column 2.
c. (if column = 3) Recognize spaces as start of column 3. Read numbers -> output to column 3.
d. (if column = 4) Recognize spaces as start of column 4. Read numbers -> output to column 4.
Each line, loop 4.
Next line does not include any numbers - End table. (probably the easiet just a user defined number, after 15 characters no number? end table)
I based my first version on Pdf to excel, but reading online people do not recommend OpenFile but rather FileSystemObject (even though it seems to be a lot slower).
Any pointers to get me started, mainly on step 2?
You have a number of ways to dissect a text file and depending on how complex it is might cause you to lean one way or another. I started this and it got a bit out of hand... enjoy.
Based on the sample you've provided and the additional comments, I noted the following. Some of these may work well for simple files but can get unwieldy with bigger more complex files. Furthermore, there may be slightly more efficient methods or tricks to what I have used here but this will definitely get you going an achieve the desired outcome. Hopefully this makes sense in conjunction with the code provided:
You can use booleans to help you determine what 'section' of the text file you are in. Ie use InStr on the current line to
determine you are in a Table by looking for the text 'Table' and then
once you know you are in the 'Table' section of the file start
looking for the 'Assets' section etc
You can use a few methods to determine the number of years (or columns) you have. The Split function along with a loop will do
the job.
If your files always have constant formatting, even only in certain parts, you can take advantage of this. For example, if you know your
file line will always have a dollar sign in front of the them, then
you know this will define the column widths and you can use this on
subsequent lines of text.
The following code will extract the Assets details from the text file, you can mod it to extract other sections. It should handle multiple rows. Hopefully I've commented it sufficient. Have a look and I'll edit if needs to help out further.
Sub ReadInTextFile()
Dim fs As Scripting.FileSystemObject, fsFile As Scripting.TextStream
Dim sFileName As String, sLine As String, vYears As Variant
Dim iNoColumns As Integer, ii As Integer, iCount As Integer
Dim bIsTable As Boolean, bIsAssets As Boolean, bIsLiabilities As Boolean, bIsNetAssets As Boolean
Set fs = CreateObject("Scripting.FileSystemObject")
sFileName = "G:\Sample.txt"
Set fsFile = fs.OpenTextFile(sFileName, 1, False)
'Loop through the file as you've already done
Do While fsFile.AtEndOfStream <> True
'Determine flag positions in text file
sLine = fsFile.Readline
Debug.Print VBA.Len(sLine)
'Always skip empty lines (including single spaceS)
If VBA.Len(sLine) > 1 Then
'We've found a new table so we can reset the booleans
If VBA.InStr(1, sLine, "Table") > 0 Then
bIsTable = True
bIsAssets = False
bIsNetAssets = False
bIsLiabilities = False
iNoColumns = 0
End If
'Perhaps you want to also have some sort of way to designate that a table has finished. Like so
If VBA.Instr(1, sLine, "Some text that designates the end of the table") Then
bIsTable = False
End If
'If we're in the table section then we want to read in the data
If bIsTable Then
'Check for your different sections. You could make this constant if your text file allowed it.
If VBA.InStr(1, sLine, "Assets") > 0 And VBA.InStr(1, sLine, "Net") = 0 Then bIsAssets = True: bIsLiabilities = False: bIsNetAssets = False
If VBA.InStr(1, sLine, "Liabilities") > 0 Then bIsAssets = False: bIsLiabilities = True: bIsNetAssets = False
If VBA.InStr(1, sLine, "Net Assests") > 0 Then bIsAssets = True: bIsLiabilities = False: bIsNetAssets = True
'If we haven't triggered any of these booleans then we're at the column headings
If Not bIsAssets And Not bIsLiabilities And Not bIsNetAssets And VBA.InStr(1, sLine, "Table") = 0 Then
'Trim the current line to remove leading and trailing spaces then use the split function to determine the number of years
vYears = VBA.Split(VBA.Trim$(sLine), " ")
For ii = LBound(vYears) To UBound(vYears)
If VBA.Len(vYears(ii)) > 0 Then iNoColumns = iNoColumns + 1
Next ii
'Now we can redefine some variables to hold the information (you'll want to redim after you've collected the info)
ReDim sAssets(1 To iNoColumns + 1, 1 To 100) As String
ReDim iColumns(1 To iNoColumns) As Integer
Else
If bIsAssets Then
'Skip the heading line
If Not VBA.Trim$(sLine) = "Assets" Then
'Increment the counter
iCount = iCount + 1
'If iCount reaches it's limit you'll have to redim preseve you sAssets array (I'll leave this to you)
If iCount > 99 Then
'You'll find other posts on stackoverflow to do this
End If
'This will happen on the first row, it'll happen everytime you
'hit a $ sign but you could code to only do so the first time
If VBA.InStr(1, sLine, "$") > 0 Then
iColumns(1) = VBA.InStr(1, sLine, "$")
For ii = 2 To iNoColumns
'We need to start at the next character across
iColumns(ii) = VBA.InStr(iColumns(ii - 1) + 1, sLine, "$")
Next ii
End If
'The first part (the name) is simply up to the $ sign (trimmed of spaces)
sAssets(1, iCount) = VBA.Trim$(VBA.Mid$(sLine, 1, iColumns(1) - 1))
For ii = 2 To iNoColumns
'Then we can loop around for the rest
sAssets(ii, iCount) = VBA.Trim$(VBA.Mid$(sLine, iColumns(ii) + 1, iColumns(ii) - iColumns(ii - 1)))
Next ii
'Now do the last column
If VBA.Len(sLine) > iColumns(iNoColumns) Then
sAssets(iNoColumns + 1, iCount) = VBA.Trim$(VBA.Right$(sLine, VBA.Len(sLine) - iColumns(iNoColumns)))
End If
Else
'Reset the counter
iCount = 0
End If
End If
End If
End If
End If
Loop
'Clean up
fsFile.Close
Set fsFile = Nothing
Set fs = Nothing
End Sub
I cannot examine the sample data as the PasteBin has been removed. Based on what I can glean from the problem description, it seems to me that using Regular Expressions would make parsing the data much easier.
Add a reference to the Scripting Runtime scrrun.dll for the FileSystemObject.
Add a reference to the Microsoft VBScript Regular Expressions 5.5. library for the RegExp object.
Instantiate a RegEx object with
Dim objRE As New RegExp
Set the Pattern property to "(\bd{4}\b){1,3}"
The above pattern should match on lines containing strings like:
2010
2010 2011
2010 2011 2012
The number of spaces between the year strings is irrelevant, as long as there is at least one (since we're not expecting to encounter strings like 201020112012 for example)
Set the Global property to True
The captured groups will be found in the individual Match objects from the MatchCollection returned by the Execute method of the RegEx object objRE. So declare the appropriate objects:
Dim objMatches as MatchCollection
Dim objMatch as Match
Dim intMatchCount 'tells you how many year strings were found, if any
Assuming you've set up a FileSystemObject object and are scanning the text file, reading each line into a variable strLine
First test to see if the current line contains the pattern sought:
If objRE.Test(strLine) Then
'do something
Else
'skip over this line
End If
Set objMatches = objRe.Execute(strLine)
intMatchCount = objMatches.Count
For i = 0 To intMatchCount - 1
'processing code such as writing the years as column headings in Excel
Set objMatch = objMatches(i)
e.g. ActiveCell.Value = objMatch.Value
'subsequent lines beneath the line containing the year strings should
'have the amounts, which may be captured in a similar fashion using an
'additional RegExp object and a Pattern such as "(\b\d+\b){1,3}" for
'whole numbers or "(\b\d+\.\d+\b){1,3}" for floats. For currency, you
'can use "(\b\$\d+\.\d{2}\b){1,3}"
Next i
This is just a rough outline of how I would approach this challenge. I hope there is something in this code outline that will be of help to you.
Another way to do this I have some success with is to use VBA to convert to a .doc or .docx file and then search for and pull tables from the Word file. They can be easily extracted into Excel sheets. The conversion seems to handle tables nicely. Note however that it works on a page by page basis so tables extending over a page end up as separate tables in the word doc.

Removing log files except for the most recent 5 using Excel VBA

My Excel VBA worksheet creates logs in a directory. Currently, the logs keep building up as I do not remove them.
However, now I would like to only keep the most recent 5. My logs are created with filenames as below:
<worksheet_name>_YYYYMMDD_HH_MM_SS.log
My current method of doing this job is to throw these logs into an array, sort the array, and keep only the first 5.
My question is this: Does anyone have a better method of keeping only the most 5 recent log files?
That sounds like a workable solution. Use the FileSystemObject library to gather all the log files, then loop thru them.
One option: you could try deleting based on Date Created or Date Modified, i.e. if the file was created over x days ago, delete it.
Also, I don't know how important these files are, but you may want to just move them to a folder called Archive instead of outright deleting them.
One system we used a while ago was to keep e.g. 5 log files with a "gap". So you would create the first 5 log files:
Files: 1,2,3,4,5
Then, on the 6th day, your gap is at 6, so create 6 and delete 1
Files: ,2,3,4,5,6
The gap is now at 1. So for the next day, create 1, and delete 2
Files: 1, ,3,4,5,6
The gap is now at 2. So for the next day, create 2, and delete 3
Files: 1,2, ,4,5,6
etc etc
i.e. "Find the Gap" *, fill it with the new file, then delete the one after it.
Just an idea.
_* (yes this is a bad joke referring to the London Underground)
Even though this is an old question, since I needed this exact solution I figured I would add it here. This code assumes that the file name ends in something that is sortable by string comparison, so that could be files of a format SomeName_YYYY-MM-DD. Twenty-four hour time stamps can be incorporated as well. This process does not rename any files, so any incremental numeric scheme will need to be carefully managed by other code (i.e. you want to add _1, _2, etc. to the file names).
Note that this solution leverages collections which serve this purpose much better than an array.
Public Sub CleanBackups(filePathAndBaseName As String, fileExtension As String, maxCopiesToKeep As Integer)
'
' Calling Example
' CleanBackups "C:\Temp\MyLog", ".txt", 5
'
' The above example would keep only the 5 versions of the file pattern "C:\Temp\MyLog*.txt"
' that are "LARGEST" in terms of a string comparison.
' So if MyLog_1.txt thru MyLog_9.txt exist, it will delete MyLog_1.txt - MyLog_4.txt
' and leave MyLog_5.txt - MyLog_9.txt
' Highly recommend using pattern MyLog_{YYYY-MM-DD_HhNn}.txt
Dim pathOnly As String
Dim foundFileName As String
Dim oldestFileIndex As Integer
Dim iLoop As Integer
Dim fileNameCollection As New Collection
pathOnly = Left(filePathAndBaseName, InStrRev(filePathAndBaseName, "\"))
foundFileName = Dir(filePathAndBaseName & "*" & fileExtension, vbNormal)
Do While foundFileName <> ""
fileNameCollection.Add foundFileName
foundFileName = Dir
Loop
Do While fileNameCollection.Count > maxCopiesToKeep
' Find oldest file, using only the name which assumes it ends with YYYY-MM-DD and optionally a 24-hour time stamp
oldestFileIndex = 1
For iLoop = 2 To fileNameCollection.Count
If StrComp(fileNameCollection.Item(iLoop), fileNameCollection.Item(oldestFileIndex), vbTextCompare) < 0 Then
oldestFileIndex = iLoop
End If
Next iLoop
Kill pathOnly & "\" & fileNameCollection.Item(oldestFileIndex)
fileNameCollection.Remove oldestFileIndex
Loop
End Sub

Resources