Omit Folders From Recursive File Search - ms-access

I was running a recursive file search procedure, and my computer shut down. I know what directory the procedure stopped at, is there a way I can specify a start folder for a recursive file search? For example, let's say this is my structure
R:\
R:\Test\
R:\Test\Folder1\
R:\Test1\
R:\Test1\Folder1\
R:\Test2\
R:\Test2\Folder2\
if I wanted the recursive search to start at
R:\Test1\Folder1\
how would the procedure go?
Option Compare Database
Sub ScanTablesWriteDataToText()
Dim Fileout As Object
Dim fso As Object
Dim objFSO As Object
Dim accapp As Access.Application
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim colFiles As Collection
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objRegExp As Object
Set objRegExp = CreateObject("VBScript.RegExp")
objRegExp.Pattern = ".jpg"
objRegExp.IgnoreCase = True
Set colFiles = New Collection
RecursiveFileSearch "R:\", objRegExp, colFiles, objFSO
For Each f In colFiles
'do something
Next
Set objFSO = Nothing
Set objRegExp = Nothing
End Sub
Sub RecursiveFileSearch(ByVal targetFolder As String, ByRef objRegExp As Object, _
ByRef matchedFiles As Collection, ByRef objFSO As Object)
Dim objFolder As Object
Dim objFile As Object
Dim objSubFolders As Object
Set objFolder = objFSO.GetFolder(targetFolder)
For Each objFile In objFolder.files
If objRegExp.test(objFile) Then
matchedFiles.Add (objFile)
End If
Next
Set objSubFolders = objFolder.Subfolders
For Each objSubfolder In objSubFolders
RecursiveFileSearch objSubfolder, objRegExp, matchedFiles, objFSO
Next
Set objFolder = Nothing
Set objFile = Nothing
Set objSubFolders = Nothing
End Sub

I'd change your recursive sub to include two more parameters -- one for the folder you're trying to find, and a boolean to indicate whether or not it's been found:
Sub RecursiveFileSearch(ByVal targetFolder As String, ByRef objRegExp As Object, _
ByRef matchedFiles As Collection, ByRef objFSO As Object, _
ByVal startFolder As String, ByVal found As Boolean)
Dim objFolder As Object
Dim objFile As Object
Dim objSubFolders As Object
Set objFolder = objFSO.GetFolder(targetFolder)
If startFolder = "" Or found Then
For Each objFile In objFolder.files
If objRegExp.test(objFile) Then
matchedFiles.Add (objFile)
End If
Next
End If
Set objSubFolders = objFolder.Subfolders
For Each objSubFolder In objSubFolders
If objSubFolder = startFolder Then
found = True
End If
RecursiveFileSearch objSubFolder, objRegExp, matchedFiles, objFSO, _
startFolder, found
Next
Set objFolder = Nothing
Set objFile = Nothing
Set objSubFolders = Nothing
End Sub
When you call it, it would be:
RecursiveFileSearch "R:\", objRegExp, colFiles, objFSO, "R:\Test1\Folder1\", false

You could short-cut this by running an (elegant) PowerShell
Dumps recursive JPG list to C:\temp\filename.csv
Sub Comesfast()
X2 = Shell("powershell.exe get-childitem ""C:\Test1\Folder1"" -recurse | where {$_.extension -eq "".jpg""} | Select-Object FullName| export-csv ""C:\temp\filename.csv"" ", 1)
End Sub

Related

Make VBA run from MS Access

I'm trying to use a macro from MS Access that #masoud wrote for me here - Reopening recently closed instances of Excel
What do I need to do to have it run from MS Access? Code has been converted to the following to suit me:
Public Sub CloseAllExcel(Close1 As Boolean)
On Error GoTo handler
Dim xl As Excel.Application
Dim wb As Excel.Workbook
Dim strPath As String
strPath = "C:\path.txt"
If Close1 Then
Dim fso as Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile as Object
Set oFile = FSO.CreateTextFile(strPath)
Do While xl Is Nothing
Set xl = GetObject(, "Excel.Application")
For Each wb In xl.Workbooks
oFile.WriteLine Application.ActiveWorkbook.FullName
wb.Save
wb.Close
Next
oFile.Close
Set fso = Nothing
Set oFile = Nothing
xl.Quit
Set xl = Nothing
Loop
Exit Sub
Else
Dim FileNum As Integer
Dim DataLine As String
FileNum = FreeFile()
Open strPath For Input As #FileNum
While Not EOF(FileNum)
Line Input #FileNum, DataLine
Workbooks.Open DataLine
Wend
Exit Sub
End If
handler:
If Err <> 429 Then 'ActiveX component can't create object
MsgBox Err.Description, vbInformation
End If
End Sub
The issues I have is that oFile.WriteLine Application.ActiveWorkbook.FullName is having a method or data member not found for the ActiveWorkbook. I'm a bit of a novice with this but I would have thought the code was good enough as is to work straight from MS Access. It works if run from Excel though.
Thanks for the help.

Access VBA search folders and Subfolders and append results to table

I'm using Access 2013 and have a small program to lookup all images in a folder path that is passed to it. It then appends each of these paths to a table called "tblImages". The only problem is it only ever returns the first image in each folder\sub folder i.e. 1 image from each folder and ignores the rest. How do I modify it to search for and append every single image in each folder\sub folder?
Public Sub listImages(folderPath As String)
'define variables
Dim fso As Object
Dim objFolder As Object
Dim objFolders As Object
Dim objF As Object
Dim objFile As Object
Dim objFiles As Object
Dim strFileName As String
Dim strFilePath As String
Dim myList As String
Dim rst As DAO.Recordset
'set file system object
Set fso = CreateObject("Scripting.FileSystemObject")
'set folder object
Set objFolder = fso.GetFolder(folderPath)
'set files
Set objFiles = objFolder.files
Set objFolders = objFolder.subfolders
'list all images in folder
For Each objFile In objFiles
If Right(objFile.Name, 4) = ".jpg" Then
strFileName = objFile.Name
strFilePath = objFile.path
myList = myList & strFileName & " - " & strFilePath & vbNewLine
End If
Next
'go through all subflders
For Each objF In objFolders
'call same procedure for each subfolder
Call listImages(objF.path)
Next
Set rst = CurrentDb.OpenRecordset("tblImages", dbOpenDynaset, dbSeeChanges)
With rst
.AddNew
.Fields("Image") = strFileName
.Fields("FilePath") = strFilePath
.Update
End With
'Debug.Print myList
Set objFolder = Nothing
Set objFolders = Nothing
Set objFile = Nothing
Set objF = Nothing
Set fso = Nothing
End Sub
You were very close. You can put this in a class module named FileSearch
Option Compare Database
Option Explicit
Private fso As FileSystemObject
Public ExtensionFilters As Dictionary
Private Sub Class_Initialize()
Set fso = New FileSystemObject
End Sub
Public Sub listImages(folderPath As String)
'define variables
Dim objFolder As Folder
Dim objFolders As Folders
Dim objF As Folder
Dim objFile As File
Dim objFiles As Files
Dim strFileName As String
Dim strFilePath As String
Dim myList As String
Dim rst As DAO.Recordset
If Not fso.FolderExists(folderPath) Then Exit Sub
'set folder object
Set objFolder = fso.GetFolder(folderPath)
'set files
Set objFiles = objFolder.Files
Set objFolders = objFolder.SubFolders
'list all images in folder
For Each objFile In objFiles
If Not ExtensionFilters Is Nothing Then
If ExtensionFilters.Exists(fso.GetExtensionName(objFile.path)) Then
strFileName = objFile.Name
strFilePath = objFile.path
AddImageToTable strFileName, strFilePath
End If
End If
Next
'go through all subflders
For Each objF In objFolders
'call same procedure for each subfolder
Call listImages(objF.path)
Next
End Sub
Private Sub AddImageToTable(strFileName, strFilePath)
Debug.Print strFileName, strFilePath
' change as needed
' Set rst = CurrentDb.OpenRecordset("tblImages", dbOpenDynaset, dbSeeChanges)
' With rst
' .AddNew
' .Fields("Image") = strFileName
' .Fields("FilePath") = strFilePath
' .Update
' End With
End Sub
and call it like this from wherever
Dim fs As New FileSearch
Dim ExtensionFilters As New Dictionary
ExtensionFilters.Add "jpg", "jpg"
ExtensionFilters.Add "jpeg", "jpeg"
Set fs.ExtensionFilters = ExtensionFilters
fs.listImages "C:\Users\bradley_handziuk\Downloads"
Also relevant is the DIR function.

MS Access VBA lookup image file names from table, search for them and copy them

I'm using Access 2013. I have a list of images in a table. I then need to search through a set of folders (including sub folders), locate the images and copy them to a new directory. The table that contains the image names does not reference the file path.
What is the best way to achieve this? Is it possible to loop through the table and perform the search, or would I have break it down and manually locate each file and update a flag to say it exists, then go back and copy them?
Not sure how to do this but would appreciate any ideas.
Thanks.
For some import programs I had to manipulate files, create copies etc. and I created some functions to help process, you might find some use in them:
To create folder from VBA:
Public Function folderCreate(filePath As String) As Boolean
'define variables
Dim fsoFold As Object
'set file system object
Set fsoFold = CreateObject("Scripting.FileSystemObject")
If Not fsoFold.folderExists(filePath) Then
'check if folder exists
fsoFold.CreateFolder (filePath)
End If
folderCreate = True
Set fsoFold = Nothing
End Function
To check if folder exists:
Public Function folderExists(folderPath As String) As Boolean
'define variables
Dim fso As Object
'set file system object
Set fso = CreateObject("Scripting.FileSystemObject")
'check if file exists
If fso.folderExists(folderPath) Then
folderExists = True
Else
folderExists = False
End If
Set fso = Nothing
End Function
To check if file exists:
Public Function fileExists(filePath As String) As Boolean
'define variables
Dim fso As Object
'set file system object
Set fso = CreateObject("Scripting.FileSystemObject")
'check if file exists
If fso.fileExists(filePath) Then
fileExists = True
Else
fileExists = False
End If
Set fso = Nothing
End Function
Similar to this, use movefile to move it to new location.
fso.movefile strFullPath, strFullBackUp
EDIT: Following sub will go through given folder and list all JPG images - this code is just example how to find files, folders and how to recursively go through them.
Public Sub listImages(folderPath As String)
'define variables
Dim fso As Object
Dim objFolder As Object
Dim objFolders As Object
Dim objF As Object
Dim objFile As Object
Dim objFiles As Object
Dim strFileName As String
Dim strFilePath As String
Dim myList As String
'set file system object
Set fso = CreateObject("Scripting.FileSystemObject")
'set folder object
Set objFolder = fso.GetFolder(folderPath)
'set files
Set objFiles = objFolder.files
Set objFolders = objFolder.subfolders
'list all images in folder
For Each objFile In objFiles
If Right(objFile.Name, 4) = ".jpg" Then
strFileName = objFile.Name
strFilePath = objFile.Path
myList = myList & strFileName & " - " & strFilePath & vbNewLine
End If
Next
'go through all subflders
For Each objF In objFolders
'call same procedure for each subfolder
Call listImages(objF.Path)
Next
Debug.Print myList
Set objFolder = Nothing
set objFolders = Nothing
Set objFile = Nothing
set objF = Nothing
Set fso = Nothing
End Sub

list files in folder and subfolders and output the result in multiple files for each parent folder

I am using the code for listing files in a folder.
Dim fso
Dim ObjOutFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set ObjOutFile = fso.CreateTextFile(GetFiles(FolderName) & "_"&"OutputFiles.csv")
ObjOutFile.WriteLine("Type,File Name,File Path")
GetFiles("YOUR LOCATION")
ObjOutFile.Close
WScript.Echo("Completed")
Function GetFiles(FolderName)
On Error Resume Next
Dim ObjFolder
Dim ObjSubFolders
Dim ObjSubFolder
Dim ObjFiles
Dim ObjFile
Set ObjFolder = fso.GetFolder(FolderName)
Set ObjFiles = ObjFolder.Files
For Each ObjFile In ObjFiles
ObjOutFile.WriteLine("File," & ObjFile.Name & "," & ObjFile.Path)
Next
Set ObjSubFolders = ObjFolder.SubFolders
For Each ObjFolder In ObjSubFolders
ObjOutFile.WriteLine("Folder," & ObjFolder.Name & "," & ObjFolder.Path)
GetFiles(ObjFolder.Path)
Next
End Function
I am getting Output as _OutputFiles.csv
If I run the script in a folder I want the output as
New Folder (3)_OutputFiles.csv
New Folder (2)_OutputFiles.csv
with all files listed.
Please suggest how to implement such that I get output for each parent folder separately.
You have to move your definition of the output file AFTER you obtain the parent folder name, and include the .Name attribute of the folder.
Dim fso
Dim ObjOutFile
Set fso = CreateObject("Scripting.FileSystemObject")
GetFiles("YOUR LOCATION")
ObjOutFile.Close
WScript.Echo("Completed")
Function GetFiles(FolderName)
On Error Resume Next
Dim ObjFolder
Dim ObjSubFolders
Dim ObjSubFolder
Dim ObjFiles
Dim ObjFile
Set ObjFolder = fso.GetFolder(FolderName)
Set ObjOutFile = fso.CreateTextFile(GetFiles(FolderName.Name) & "_"&"OutputFiles.csv")
ObjOutFile.WriteLine("Type,File Name,File Path")
Set ObjFiles = ObjFolder.Files
For Each ObjFile In ObjFiles
ObjOutFile.WriteLine("File," & ObjFile.Name & "," & ObjFile.Path)
Next
Set ObjSubFolders = ObjFolder.SubFolders
For Each ObjFolder In ObjSubFolders
ObjOutFile.WriteLine("Folder," & ObjFolder.Name & "," & ObjFolder.Path)
GetFiles(ObjFolder.Path)
Next
End Function

Loop through for all shortcuts in a given location and return the target path

Is it possible to loop through for all shortcuts (.lnk) in a given location and return the .TargetPath. If a shortcuts target matches a criteria an action can then be peformed on the shortcut?
To delete all shortcuts I would use the following:
Public Sub deleteAllShortcuts()
Dim shortCutPath As String
' compName = Computer Name, recordDirShort = directory where the shortcut lnks are
shortCutPath = compName & recordDirShort
shortCutPath = shortCutPath & "*.lnk"
On Error Resume Next
Kill shortCutPath
On Error GoTo 0
End Sub
I cant figure out how I would loop through all shortcuts in the directory using the above loop.
Any help on the above would be greatly appreciated
Cheers
Noel
Hopefully this may be good to someone.
To delete shortcuts by the shorcut target I used the following:
Public Sub deleteShortcutByTarget(targetFolderName As String)
Dim strDocPath As String
Dim strTarget As String
Dim obj As Object
Dim shortcut As Object
Dim objFso As Object
Dim objFolder As Object
Dim objFile As Object
Set obj = CreateObject("WScript.Shell")
Set objFso = CreateObject("Scripting.FileSystemObject")
strDocPath = compName & recordDirShort
Set objFolder = objFso.GetFolder(strDocPath)
Set objFile = objFolder.Files
For Each objFile In objFolder.Files
If objFso.GetExtensionName(objFile.Path) = "lnk" Then
Set shortcut = obj.CreateShortcut(objFile.Path)
strTarget = shortcut.TargetPath
shortcut.Save
If strTarget = strDocPath & targetFolderName Then
Kill objFile.Path
End If
End If
Next
Set obj = Nothing
Set objFile = Nothing
Set objFso = Nothing
Set objFolder = Nothing
Set shortcut = Nothing
End Sub
Within Access you could use the Dir() function. It would be something like this:
Dim strLink As String
strLink = Dir(shortCutPath & "*.lnk")
Do Until Len(strLink)=0
Kill strLink
strLink = Dir()
Loop
Dir() doesn't play well with network paths in all cases, though, so you might want to use the File System Object, instead. It's much more versatile and works better with networks. I use it only occasionally, so don't have the code at my fingertips, but have a look at it -- you might have no trouble figuring it out as the object model is pretty clearly designed.