Ark68
Well-known Member
- Joined
- Mar 23, 2004
- Messages
- 4,650
- Office Version
- 365
- 2016
- Platform
- Windows
I have this function which scours all the folders on a drive looking for a a file that contains a particular string (a substring of the file name). Example: To find the file "Sahara - Fine Grantite.docx", the variable SearchFileName would be "- Fine Granite." . This excludes any text before the hyphen, and after the period. (all filenames in the directory have the same format "text - text.ext"). The directory path of the individuals files follows this pattern:
O:\Science\{x}\{y}\{files} where {X} and {Y} are variable.
This code is not finding the right file. It's stopping the search at the first file directory {Y}. I think I have my InStr code wrong, but am at a brain lapse to figure out the error. For example, the file "Sahara - Fine Grantite.docx" is stored in O:\Science\S\Sahara\. SearchFileName = "- Fine Granite.". sfResult returns a value of "O:\Science\A\Andretti\Andrettit - Amethyst.docx"
O:\Science\{x}\{y}\{files} where {X} and {Y} are variable.
This code is not finding the right file. It's stopping the search at the first file directory {Y}. I think I have my InStr code wrong, but am at a brain lapse to figure out the error. For example, the file "Sahara - Fine Grantite.docx" is stored in O:\Science\S\Sahara\. SearchFileName = "- Fine Granite.". sfResult returns a value of "O:\Science\A\Andretti\Andrettit - Amethyst.docx"
Rich (BB code):
Function SearchInFolder(Folder As Object, SearchFileName As String) As String
Dim SubFolder As Object
Dim File As Object
'Stop 'SearchFileName
On Error Resume Next
'Stop 'searchfilename
' Loop through each file in the current folder
For Each File In Folder.Files
'Debug.Print Folder
If Err.Number = 70 Then
Err.Clear
Exit For
End If
'If StrComp(File.Name, SearchFileName, vbTextCompare) = 0 Then
If InStr(File.Name, SearchFileName, vbTextCompare) <> 0 Then 'changing this to = 0 nets the same results
SearchInFolder = File.Path
Exit Function
End If
Next File
' Loop through each subfolder
For Each SubFolder In Folder.SubFolders
Debug.Print SubFolder
If Err.Number = 70 Then
Err.Clear
Exit For
End If
SearchInFolder = SearchInFolder(SubFolder, SearchFileName)
If SearchInFolder <> "File not found" Then Exit Function
Next SubFolder