As a preface, I'm writing code in Access 2003, but will have users using Access 2013, and so I need it to be compatible for both. I have a loop that uses the Application.FileSearch to loop through a number of files in a directory. It is my understanding that this is deprecated in newer version of Access, and so I have to use "For Each" to loop through files.
Here's the piece of code I'm changing:
strPath = CurrentProject.Path & "\Files\"
strFileName = "SourceCode.txt"
With Application.FileSearch
.FileName = "*.txt"
.LookIn = strPath
.Execute
intFileCount = .foundfiles.Count
For x = 1 To intFileCount
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(.foundfiles(x))
strNewFileName = Right((.foundfiles(x)), Len((.foundfiles(x))) - (InStr((.foundfiles(x)), "Files\") + 5))
fs.MoveFile f, strPath & strFileName
'Run the Process() function
Process
FileCopy strPath & strFileName, strPath & "Processed\" & strNewFileName
Kill strPath & strFileName
Next x
End With
And here's the code I'm replacing it with:
strPath = CurrentProject.Path & "\Files\"
strFileName = "SourceCode.txt"
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFolder(strPath)
Set fc = f.Files
For Each f1 In fc
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strPath & f1.Name, 1)
strNewFileName = f1.Name
f1.Name = strFileName
'Run the Process() function
Process
FileCopy strPath & strFileName, strPath & "Processed\" & strNewFileName
Kill strPath & strFileName
Next
This code loops through each file, then launches a Process() function that makes changes to the file. So the way I have it working is it changes the active file to be named "SourceCode.txt", then the Process() function knows to work with the file of that name. Then it moves the file to the "Processed" subfolder, with its original file name.
This worked fine in the original code. The new code seems to mostly work, except I can't find a way to rename the file to "SourceCode.txt" prior to launching Process(). I tried several ways but I keep getting errors. In the code above, I tried "f1.Name = strFileName". This gives me a "Permission Denied" error. I tried alternatively to use FileCopy, and then the Kill command on the original file, but the Kill command returned an error. I suspect the FileSystemObject is locking the file so it can't be moved or killed. But the old version of the code was able to move it with no problem.