Looping over all databases in a directory - vb6

I need to loop over all databases in a certain directory, where the database name is ACPwxyz.mdb, where wxyz is the equivalent to an MMYY value for the period that database was used for.
E.g., the database for July 2017 would be ACP0717.mdb.
I've never written in VB6 before and I totally hate it, but it's an extension to an existing project so I'm stuck with it!
Is there a way of looping over all files in a directory, checking if the file name follows the format of ACPwxyz.mdb or not, and if it does, then opening a connection to it?
I've looked around a bit and see Dir(x, y), but I'm not sure if I can use this in this situation?
Any tips would be appreciated.

You can use Dir, yes.
If you use something like this:
Dim strFile As String
strFile = Dir(yourDBPath, "ACP????.mdb") ' mdb for MS-Access files
Do Until strFile = ""
If Len(strFile) = 11 Then ' Ensure the DB file name is 11 characters, which yours are
'Do something // You can also check the file name doesn't = a certain name if needed
End If
strFile = Dir
Loop
Dir accepts either an asterisk (*), or a question mark (?) as wildcards in file names, so this will look for any database in the set path that is called ACP followed by 4 characters.

Related

How do I rename and move a file downloaded to 'Downloads" using Automator, with or without Applescript, Shell Script or Javascript?

I am a newbie to programming and therefore please excuse my lack of knowledge. I have trawled the site and the internet but have not found an answer to what seems like a simple problem.
I would like to automate the filing and renaming of some personal and business documents - they are bank statements so the numbers are anonymised. I am interested in understanding the code so I can adapt it after too, for further actions (and maybe for others to use).
The documents are downloaded into the (mac) downloads folder. Typically they have this name: "Statement--12345678--98765432--1-06-2020-30-06-2020.pdf" The two sets of numbers at the beginning are not these generic ones but there are 8 figures (though the first number sometimes is not listed as it is a "0"). The second set of two numbers refers to two dates, in day--month--year format. Sometimes the first date starts on the last day of the previous month!
As a newbie I started with Automator - using a Folder Action to move the individual files to a named folder (by year). I then wanted to rename them so that the second date comes first in the name in YYYYMMDD format, so that they will automatically be listed in date order in the year folder. The full name would become "YYYYMMDD 98765432 Month YY".
I can move the files and automatically (thanks to automator); I can even add the current date at the beginning of the name in the right format (but it will be the current date not the date in the file). But I cannot do what I really want: change the name based on the date in the filename.
I then looked at AppleScript. The answers below solve the naming problem - THANK YOU!
But when I try to pick up a bunch of files - there are 25 of them (happily found and moved by Automator (Find files and Move files) the output is not recognised as an input into AppleScript. I get "Can't get files XXXX as alias" or if I try to create a variable, that is not defined (though I have tried numerous times... as {}, as "", as item 1 of input).
I do apologise if this is not clear, but I am trying my best to explain it, and do not understand terms such as 'terminal ls'.
Any help, advice and commentary gratefully received. I really do want to try to understand the code so I can apply the learning! Thank you,
John
Okay, your problem is to extract multiple parts of the name.
The trick is to explode it into small parts. GREP is a good tool, but tricky with applescript "out of the box".
I use a subroutine called "textSplit" to do the job. Once every part of the filename is available in variables, you should be able to build any file or folder name...
Here's my way to solve this :
set thisFileName to "Document--12345678--98765432--1-06-2020-30-06-2020.pdf"
-- first we split the name using the "--" separator
set mainParts to textSplit(thisFileName, "--")
-- we now copy the result to variables to handle it
copy mainParts to {prefixOne, numberOne, numberTwo, theTwoDates}
--> prefixOne = "Document"
--> numberOne = "12345678"
--> numberTwo = "98765432"
--> theTwoDates = "1-06-2020-30-06-2020.pdf"
-- get rid of the extension
set theDatesWithoutExtension to first item of textSplit(theTwoDates, ".")
-- split the dates
set splitDates to textSplit(theDatesWithoutExtension, "-")
-- copy result into nice variables
copy splitDates to {dayOne, monthOne, yearOne, dayTwo, monthTwo, yearTwo}
-- and then build the filename with whatever you want
set myNewFileName to yearOne & monthOne & dayOne & space & numberTwo & space & monthTwo & "-" & yearTwo & ".pdf"
--> "2020061 98765432 06-2020.pdf"
-- make folders, move files, renameā€¦
-- ================================================================================================
on textSplit(theText, theDelimiter)
-- this will split a string and returns a list of substrings
set saveDelim to AppleScript's text item delimiters
set AppleScript's text item delimiters to {theDelimiter}
set theList to every text item of theText
set AppleScript's text item delimiters to saveDelim
return (theList)
end textSplit

Comparing files in two different folders with string variable names

Due to automatic naming conventions I'm stuck with, files are saved in a particular archive one of two ways. Either they have a 13-digit match to the record in the database, or they have a 10 digit match. The ones which have the 13 digit also have the ten digit match, and should be treated preferentially. I have two scripts right now that work: one just looks for 13-digit matches and moves them to another folder. The other moves by datemodified, which is not a very stable variable.
My attempts at combining look something like this:
'dimming of obj, folder paths, sql db info and connection open above
SQL = "SELECT ticket FROM orders WHERE dateinvoice>'6/1/16"
Recordset.Open SQL, Connection
Do While Not Recordset.EOF
ticket = Recordset("ticket")
id = Right(ticket, 2)
suffix = CInt(id)
compare = Left(ticket, Len(ticket) - 3)
search = compare & "-0" & suffix
For Each objFile In colFiles.Files
If Left(objFile.Name, 13) = search Then
Set objNewestFile = objFile
skip = 1
Else
skip = 0
End If
If Left(objFile.Name, 10) = search And skip = 0 Then
Set objNewestFile = objFile
End If
Next
Recordset.MoveNext
On Error Resume Next
objFSO.CopyFile objNewestFile.Path, strDestFolder
Set objFile = Nothing
Loop
This is the scaled-down version I went back to, having attempted various convoluted solutions like:
storing the skipped records in an array,
having a second loop through comparing files in folder1 to folder2 (every time I use FileExists it doesn't seem to recognize the destination),
creating a temporary SQL table to store the skipped records in.
The following have been very useful:
Compare two files in two different folders and replace it by the newer
https://blogs.technet.microsoft.com/heyscriptingguy/2005/06/20/how-can-i-determine-if-a-file-exists-and-if-it-does-exit-the-script/
Classic ASP 3.0 Create Array from a Recordset
ETA: There can be many duplicate files that share the 10 digit identifier. The only good rule is: if it has the 13 identifier version, that's the one to move. Part of my issue lies in setting paths if I use FileExists-- when I try wildcards, it doesn't recognize the path. If I don't use them, it doesn't compensate for all the variables.

Move files to folders based on first X characters of filename (vbs)

Hello my coding friends.
Sorry to ask this, but I thought it might be quicker to ask if someone has a script like this lying around.
I have about 2000+ files of audio mp3 files logged for a radio station I'm at, and I'd like to put them in to folders according to their recorded log date.
(Yes, I've now fixed the recording to do this correctly from now on, but this is in referent to what I've been doing with it: https://stephenmonro.wordpress.com/2015/05/22/setting-up-an-audio-logger/ )
The files I have are like this: (YYYYMMDD_HH00)
logs\20150424_0300.mp3
logs\20150424_0400.mp3
logs\20150424_0500.mp3
etc.
What I'd like is something like this:
\logs\8 digit date\filename with the same 8 digit date.mp3
Actual
\logs\20150424\20150424_0300.mp3
\logs\20150424\20150424_0400.mp3
\logs\20150424\20150424_0500.mp3
etc.
This is my pseudo code, I've made, but as I'm a little pressed for time and don't have hours to mess around guessing, I just wondered if anyone knew how to do it quickly.
A .VBS file is my prefered language.
Do
Read a filenames first 8 characters {left(8, filename)} (the date)
If not exist, create a folder called that first 8 characters
Move that file into the folder name
Loop (until all files are moved to the right locations)
Your pseudocode looks spot on to me. Assuming every file in your logs folder is consistently named, here's how it could be accomplished using the FileSystemObject library:
Const LOGS_FOLDER = "c:\logs"
Dim objFSO, objFile, strDate, strSub
Set objFSO = CreateObject("Scripting.FileSystemObject")
For Each objFile In objFSO.GetFolder(LOGS_FOLDER).Files
strDate = Left(objFile.Name, 8)
strSub = objFSO.BuildPath(LOGS_FOLDER, strDate)
' Create the folder if it doesn't already exist...
If Not objFSO.FolderExists(strSub) Then objFSO.CreateFolder strSub
' Move the file into its proper folder. Use "\" to indicate dest is folder...
objFile.Move strSub & "\"
Next

needing help creating a script to find if a folder has been modified in the last day and if not create a txt file in a location

I'm trying to create a script that finds if a folder hasn't been modified in the last day and create a text file in a location. However if it has been modified in the last day I want it to quit the script.
At the moment, I have only been able to create one (due to my basic knowledge of VBscripting) that finds if a folder exists and if so creates a script.
This however, doesn't work as the subfolder is created daily with a new name and obviously this means my script would have to be changed daily which is pointless.
I need to have the parent folder read and a text file created in another locationif the last modified date isn't < 1 day.
This is the script so far:
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists("c:\test") Then
wsscript.quit
Else
dim filesys, filetxt, getname, path
Set filesys = CreateObject("Scripting.FileSystemObject")
Set filetxt = filesys.CreateTextFile("c:\test\test.txt", True)
path = filesys.GetAbsolutePathName("c:\test\test.txt")
getname = filesys.GetFileName(path)
filetxt.WriteLine("file doesnt exist.")
filetxt.Close
End If
I know I need to change the .folderExists line to something like
if file.DateLastModified > dateadd("h", -24, Now) then
I would like a day parameter rather than an hour; I know this means turning the h into a d but I am unsure past that.
it has been solved by Mr Bond! the wonderful man he is. however i now have another question, any idea how to add a command to send an outlook email into this? as the else option.
Use the DateLastModified property of the Folder object.
If objFSO.GetFolder("c:\test").DateLastModified >= Date - 1 Then
' Folder modified within last day
Else
' Folder modified more than a day ago
End
There's no need to use DateAdd() to add/subtract days. You can just use integer arithmetic.
Note that this will yield a time of zero/midnight. So it's really checking to see if the folder was modified since the start of the day yesterday, not in the last 24 hours. That may or may not be what you want.

Search filesystem for filepath using VBA

I am looking for a way to search a specific folder for a subfolder containing a certain string. Below I have listed a function I typed off the top of my head to see if it would work. Well, it does work but when I am talking about searching through 6,000 folders on a network drive it just isn't fast enough.
I'm sure that there is a better way to do it but I can't seem to dig anything up on Google.
Is there an object that allows me to leverage the windows built in file system searching and indexing capabilities?
As an alternative, does someone have a way to optimize my code? The main bottleneck is the usage of instr.
Here is the code:
Function findPath(strId As String) As String
checkObj
Dim strBase As String
strBase = opt.photoBasePath
Dim fs As Object
Set fs = CreateObject("Scripting.FileSystemObject")
Dim baseFolder As Object
Set baseFolder = fs.getfolder(strBase)
Dim folder As Object
For Each folder In baseFolder.subfolders
If InStr(1, folder.name, strId) > 0 Then
findPath = strBase & "\" & folder.name
Exit Function
End If
Next folder
End Function
P.S. I'm sure someone will suggest modifying my folder structure so that I can programmatically predict the path but for various reason that isn't possible in my case.
You could use the FindFirstFile Win32 API, which allows you to search for files or sudirectories matching a specified name. Additionally, you could also use the FindFirstFileEx function, along with a FINDEX_SEARCH_OPS parameter of FindExSearchLimitToDirectories, which would limit your search to a file that matches a specified name and is also a directory (if the file system supports directory filtering). For more information on using these functions from VB/VBA see the following:
http://www.xtremevbtalk.com/showpost.php?p=1157418&postcount=4
http://support.microsoft.com/kb/185476
http://www.ask-4it.com/how-to-use-findfirstfile-win32-api-from-visual-basic-code-2-ca.html
Consider splitting traversing the folders from finding your key. Instead of the instr test, store the folder names in a table, then use a query on the table to find your target. It might be slower, but searching should be faster.

Resources