I am trying to find a way using Access 2003 (Yes I know this is ancient), to search all the sub directories of a folder to determine if a file exists. If it is found it needs to be entered into a sub that turns a button on or off. I would also like to be able to save the path as I would need this button to link to a file. So as a brief explanation, using Access I would like to search a folder a drive which has sub folders which each has their own sub folders. I found many websites, including the following one, but none of the answers seems to work.
Loop Through All Subfolders Using VBA
Any help will be appreciated.
`Dim FileSystem As Object
Dim HostFolder As String
HostFolder = "C:\"
Set FileSystem = CreateObject("Scripting.FileSystemObject")
DoFolder FileSystem.GetFolder(HostFolder)
Sub DoFolder(Folder)
Dim SubFolder
For Each SubFolder In Folder.SubFolders
DoFolder SubFolder
Next
Dim File
For Each File In Folder.Files
' Operate on each file
Next
End Sub`
Gives me an invalid procedure and says the error is in the host folder I used. However, it is the same one I have used for my other codes samples with no problems.
Public Sub NonRecursiveMethod()
Dim fso, oFolder, oSubfolder, oFile, queue As Collection
Set fso = CreateObject("Scripting.FileSystemObject")
Set queue = New Collection
queue.Add fso.GetFolder("your folder path variable") 'obviously replace
Do While queue.Count > 0
Set oFolder = queue(1)
queue.Remove 1 'dequeue
'...insert any folder processing code here...
For Each oSubfolder In oFolder.SubFolders
queue.Add oSubfolder 'enqueue
Next oSubfolder
For Each oFile In oFolder.Files
'...insert any file processing code here...
Next oFile
Loop
End Sub
Gives me an error because the last next isn't in a for loop according to Access VBA.
I found another code that I was able to get working. It is from the website
http://www.ammara.com/access_image_faq/recursive_folder_search.html
However, this is extremely slow. Takes 30 seconds to run yet, when everything was in a single folder, a simple dir check would be instantaneous. Thanks to those who offered some help.
Related
I'm running an Excel VBA macro. It includes the following code:
Private Sub ListTheFiles(inFldr as Scripting.Folder)
Dim fl as Scripting.File, subfldr as Scripting.Folder
If inFldr.Files.Count > 0 then
For Each fl in inFldr.Files
'List the file and its size and LastModifiedDate on a worksheet, making no changes to the file
Next fl
End If
For Each subfldr in inFldr.Subfolders
ListTheFiles subfldr
Next subfldr
End Sub
The module runs this subroutine hundreds of times, usually successfully. But for just a couple of folders, it reaches the first "For Each" (which indicates there ARE files in inFldr), but then it skips right to the "End If" without processing any files. The two folders that don't get processed each contains 12 PDF files and no other files and no subfolders. Many of the other folders also contain PDF files only, and they work fine.
Why would this happen? Thanks.
List Files in a Folder and in Its Subfolders
I am using this without a reference to the Scripting FileSystemObject object. As you can see, the 'recursion' code is 'basically' the same (except for the .Count). You could test it, to see if the issue repeats itself.
The Code
Option Explicit
Sub FilesRecurseTEST()
Const FolderPath As String = "F:\Test\2021"
Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
FilesRecurse fso.GetFolder(FolderPath)
End Sub
Sub FilesRecurse( _
fsoFolder As Object)
Dim fsoSubFolder As Object, fsoFile As Object
For Each fsoFile In fsoFolder.Files
With fsoFile
Debug.Print .Name, .Size, .DateLastModified
End With
Next fsoFile
For Each fsoSubFolder In fsoFolder.Subfolders
FilesRecurse fsoSubFolder
Next
End Sub
I am trying to get access the share point folder and files using VBA.
I have tried the same code to access the local folders and files it was working perfectly fine.
Here is my folder structure from share point. I need to access all the files inside the folder
Mainfolder
Folder 1
Folder 2
Folder 3
Folder 4
Option Explicit
Sub Somesub()
Call GetFiles("https://isharenew.xyz.com/main folder \")
End Sub
Sub GetFiles(ByVal path As String)
Dim spSite As String
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim folder As Object
Set folder = fso.GetFolder(path)
Dim subfolder As Object
Dim file As Object
For Each subfolder In folder.SubFolders
GetFiles (subfolder.path)
Next subfolder
For Each file In folder.Files
Range("L" & Rows.Count).End(xlUp).Offset(1, 0) = file.path
Next file
Set fso = Nothing
Set folder = Nothing
Set subfolder = Nothing
Set file = Nothing
End Sub
With my above code I am getting error Path Not Found
Please let me know where I am doing mistake.
I am fairly new to VBA and any help with this program is greatly appreciated!
The goal of this program is to copy all specific file types (.pdf) from the network to a folder on the desktop. However, the (.pdf) files are in each of the folders subfolders.
If I have the user define the folder (with the many subfolders), I would like the program to copy each .pdf from each subfolder into the target folder.
This is what I have gotten so far from browsing the internet.
Sub Copy_test2()
Dim FSO As Object, fld As Object
Dim fsoFile As Object
Dim fsoFol As Object
FromPath = "D:\Users\A\Desktop\test1" 'user will define this
ToPath = "D:\Users\A\Desktop\test2" 'this will be the folder on the desktop
If Right(FromPath, 1) <> "\" Then
FromPath = FromPath & "\"
End If
Set FSO = CreateObject(“Scripting.FileSystemObject”)
Set fld = FSO.GetFolder(FromPath)
If FSO.FolderExists(fld) Then
For Each fsoFol In FSO.GetFolder(FromPath).subfolders
For Each fsoFile In fsoFol.Files
If Right(fsoFile, 3) = “pdf” Then
fsoFile.Copy ToPath
End If
Next
Next
End If
End Sub
When I run it, I get : Run-time Error '424' Object Required for
Set FSO = CreateObject(“Scripting.FileSystemObject”)
Am I going about this code the right way? or is there alternative method to accomplish this task?
Thanks!
Always begin your modules with Option Explicit. This forces you to declare all variables, which is a great thing.
Then, always compile your code before running it. This can be done from the Debug menu -> Compile. In your case, compilation will fail because a couple string variables are not declared (unless they're declared at the module level), and because you're using double quotes that aren't ", i.e. “ and ”. See the difference? VBA doesn't like them :-)
I want to know if it's possible to rewrite this piece of code:
Private Sub PrepareDir(ByVal dir As String)
Dim fso As New FileSystemObject
If fso.FolderExists(dir) Then Call fso.DeleteFolder(dir, True)
Call fso.CreateFolder(dir)
End Sub
With VBA statements: Kill, MkDir, etc. Most "difficult" part of this - remove non-empty directory. With FSO it can be done easily, but how it can be done without FSO?
The OP said they want to rewrite their code "without FSO" but it doesn't make sense.
If the goal is to reduce the amount of code, simply make it a one-liner:
CreateObject("Scripting.FileSystemObject").DeleteFolder "x:\myFolder"
As requested, this permanently removes the folder and it's contents.
More Information:
Microsoft Docs : DeleteFolder Method
Ron de Bruin : Delete files and folders
This piece of ccode uses RmDir to remove the Folder. AFAIK, RmDir cannot delete the folder unless it is empty, so we first clear the content in the folder then remove the directory.
Private Sub PrepareDirModified(dirStr As String)
On Error Resume Next
If Right(dirStr, 1) <> "\" Then dirStr = dirStr & "\"
Kill dirStr & "*.*"
RmDir dirStr
MkDir dirStr
On Error GoTo 0
End Sub
Hope this helps.
No need to delete files for Deleting folders.
Take the path and search for the sub folders in a loop and that sub folder can be deleted.
below is the example :copy both procedures and paste on module
Public Function Delete_Folder(ByVal FldrName As String)
Dim fso, FSfolder As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set FSfolder = fso.GetFolder(Application.DefaultFilePath)' This is My Documents folder path
'You can replace with your original folder path
For Each Folder In FSfolder.SubFolders
'Debug.Print Folder.Name
If Folder.Name = FldrName Then
Folder.Delete
Exit For
End If
Next
End Function
Sub test()
Delete_Folder "Sub_Folder_Name"
End Sub
I have a number of excel (.xls) stored in a folder in a local drive. I need to do some process to every file in this folder. What is the code that will
loop through every file
open the file
Do some processing and then Save & close the file
move the file to another folder after processing
To be more clear, I want go over every file and do processing to it. After finishing a file, go to another file and so till the end of all the files in the folder. I do have the code for the processing; I just need to know the code that will loop through the files and move then to another folder.
Thanks for your help in advance,
What you need is a recursive function that iterates over the tree that represents a file system. It means to iterate over all the childs of some 'parent folder'. I send you a function that does something similar, to the one you need (this is currently in usage). This function deletes all the empty folders given a parent folder.
Public Function gf_DeleteEmptyFolder(path As String) As Boolean
On Error GoTo Error_Handler
Dim fso_folder As Scripting.Folder, sub_folder As Scripting.Folder
If g_FSO.FolderExists(path) Then
Set fso_folder = g_FSO.GetFolder(path)
'-- eliminates de folder only if is empty
If 0 = fso_folder.Files.Count And 0 = fso_folder.SubFolders.Count Then
Call g_FSO.DeleteFolder(path, False)
'-- recursively calls the function
Else
For Each sub_folder In fso_folder.SubFolders
Call gf_DeleteEmptyFolder(sub_folder.path)
Next
End If
End If
gf_DeleteEmptyFolder = True
Exit Function
'~~~ on error
Error_Handler:
gf_DeleteEmptyFolder = False
End Function
If your files are stored in a simple folder, then you can use the following code to iterate each file.
Public Sub fsoProcessFilesInFolder(sFolder As String)
Dim fso As Scripting.FileSystemObject, fld As Scripting.Folder, fil As Scripting.File
Set fso = New FileSystemObject
Set fld = fso.GetFolder(sFolder)
For Each fil In fld.Files
'--- add code to process your files
Next fil
End Sub
Here's the easy VBA object way to do it:
Dim fs As FileSearch
Dim i As Integer
Dim wbk As Workbook
Set fs = Application.FileSearch
With fs
.LookIn = ThisWorkbook.Path
.FileName = "*.xls"
For i = 1 to .Execute()
Set wbk = Workbooks.Open(.FoundFiles(i))
''//DO STUFF HERE
wbk.Close(SaveChanges:=True)
Next i
End With
In VB6 you have three options, as shown in the following KB articles:
How to Search Directories to Find or List Files
HOW TO: Recursively Search Directories by Using FileSystemObject
The following code will read xlsx/xls files from given folder neglecting other files and iterate through each item.
You can use it for any set of extensions and filters.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(folderPath)
Set objFiles = objFolder.Files
'Iterate through the files in the folder
For Each Item In objFiles
If LCase(Right(Item.Name, 5)) = ".xls" Or LCase(Right(Item.Name, 4)) = ".xlsx" Then
''''''Do Stuffs Here''''''
End If
Next