Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

Search file in whatever directory with vba

0

Hi, I watched the following video but could not solve my issue:

Working with Workbooks > Check if a Workbook Exists and is Open - Prevent Errors

URL = https://www.teachexcel.com/premium-courses/79/excel-vba-course-beginner-to-expert?i=2364

starting at 00:40 and ending at 02:20. The example shows how to find a given filename with a well defined path ("C:\Test\")

I'm looking for a way, using VBA, to find a known filename but I have no clue in which directory it is saved. I would like to start the search for the known filename by looking in every directory starting from "C:\".

I created an excel file in order to manage a small membership  database. I passed over this file to a collegue of mine which is the final user. The programming is not finished yet and from time to time I update the code to a new version in my computer, in order to substitute the old one withe updated one, but I don't know where he saved the file on his computer.

My goal is to find the older file in use, open it, copy the last saved sheets into the new updated  workbook, save the new workbook in the same position (path) of the old one and delete the old one.

Is that possible?

I hope this clarifies issue.

Many thanks in advance for help.

Answer
Discuss

Discussion

Valentino

I don't recognise the video "Working with Workbooks > Check if a Workbook Exists and is Open - Prevent Errors" and your question doesn't include the URL. Kindly edit your original question to correct that.

Willie has provide a non-VBA merthod but it is definitley possible to use VBA to search folders for a known file name or partial filename- which do you need?

Note that it could be quite time consuming if you have a large drive and you might be better using dedicated search tools unless you plan to open and/or extract data from the found files- is this a requirement toio?
John_Ru (rep: 6417) Aug 10, '24 at 7:21 am
I updated the post, hoping it is more understandable now.
Valentino (rep: 2) Aug 10, '24 at 10:03 am
Thanks. Please see my Answer / file. 
John_Ru (rep: 6417) Aug 10, '24 at 3:09 pm
Add to Discussion

Answers

0
Selected Answer

Valentino

Thanks for clarifying your question. I'll give a generic answer but will NOT refer to the file/ URL mentioned in your question- if you have questions on a paid VBA course, please don't post them (or code/ files) here or elsewhere. Instead use the Contact link (in the green bar above) and use the Premium Courses option. Don will then answer you directly but allow him some time- he's a busy man!

In the file attached, there are two procedures in Module1. That starts with some declarations (which define and allow items to be shared between the two procedures):

Public ObjFolder As Object, objSubFile As Object
Public objFso As Object
Public objFldLoop As Object
Public TargName As String

 

Then the first procedure is where you define what to search for and where (via the  bold comments and bits in quotation marks below):

Sub GetStructure()

    ' enable use of FSO
    Set objFso = CreateObject("Scripting.FileSystemObject")

    '### define top level folder path
    Set ObjFolder = objFso.GetFolder("E:\Documents\Spreadsheets\TeachExcel files\")
    ' ### define the partial of full name of *.xlsm target file (without extension)
    TargName = "letters"
    ' make sure at least 5 characters in names
    If Len(TargName) < 5 Then Exit Sub



    ' loop through this folder
    For Each objSubFile In ObjFolder.Files
        ' check it's a macro file and matches target name
        If Right(LCase(objSubFile.Name), 5) = ".xlsm" _
            And InStr(LCase(objSubFile.Name), LCase(TargName)) > 0 Then
            ' print in Intermediate window
            Debug.Print "* Found:  " & objSubFile.Name & vbCr & " at " & objSubFile.Path
        End If
    Next objSubFile
    ' call the function to loop through its subfolders (and theirs)
    LoopEachFolder ObjFolder

    ' quit FSO
    Set objFso = Nothing

End Sub

After running through the top-level folder, that passes that folder name to the function below (which calls itself iteratively):

Function LoopEachFolder(fldFolder As Object)

    ' With the subfolders in this folder....
    For Each objFldLoop In fldFolder.subFolders
        ' ...loop through files in this folder
        For Each objSubFile In objFldLoop.Files
            ' check it's a macro file and matches target name
            If Right(LCase(objSubFile.Name), 5) = ".xlsm" _
                And InStr(LCase(objSubFile.Name), LCase(TargName)) > 0 Then
                ' print in Intermediate window
                Debug.Print "* Found:  " & objSubFile.Name & vbCr & " at " & objSubFile.Path
            End If
        Next objSubFile
        ' ... and run the function on each subfolder found
        LoopEachFolder objFldLoop

    Next objFldLoop

End Function

It will search every folder and subfolder below the top-level folder you define (but may take some time!).

In my case I was searching for .xlsm file including  the string "letters" in my folder  E:\Documents\Spreadsheets\TeachExcel files\ (which you might change to C:\ on your user's computer).

When you run the first procedure, it will print one or more results like that below (in VBA's Immediate Window, in which you can copy text):

* Found:  Get letters from numbers and select multiple columns v0_a.xlsm
 at E:\Documents\Spreadsheets\TeachExcel files\Tutorial files\Get letters from numbers and select multiple columns v0_a.xlsm

You'll need to change "letters" for as much as you know EXACTLY about the user's file name but note I included a line which means it does nothing unless that string had 5 characters or more (otherwise you're likely to get many matches).

Hope this fixes your problem. If so, please be sure to mark this Answer as Selected.

Discuss

Discussion

Many thanks for the answer and the code John. I will try to understand it and try it out on my workbook. If anything, I will revert and inform you what happened. Valentino
Valentino (rep: 2) Aug 12, '24 at 4:36 am
Hope that works out for you, Valentino. Thanks for selecting my Answer.

If it proves very slow AND you always know the exact file name (or the user can't change it), a much faster search could be done with the VBA function Dir function. 
John_Ru (rep: 6417) Aug 12, '24 at 5:21 am
Also, if the user uses the file often, you might find it in the Recently Used Files lust in Excel and get the location without a VBA search (or just open it from there, replace the code and save
John_Ru (rep: 6417) Aug 12, '24 at 5:25 am
Add to Discussion
0

 Hello Valentino and welcome to the forum,

If you are looking to search manually for the file you can use Windows search utility.

In the search field type the name of the file ( MyMissingFile.xlsm ) and the file will be returned in the results. From there you can open the file. After the file is open go to "File" >> "Info" and in the lower right select "Open File Location" and you will learn where the file is located. After the has been closed, the file should now be listed in the file explorer where you can right cklick the name and choose "Open File Location" to learn where the file is located.

If this answers your question please mark my answer as selected.

Cheers   :-)

Discuss

Discussion

Many thanks for your answer WillieD24 but I'm looking for a solution working with VBA. As suggested by John_Ru I amended my question for better understanding. (At least I hope so...)
Valentino (rep: 2) Aug 10, '24 at 10:07 am
Hi Valentino,
I understand your desire to do this search using VBA as it would reduce the number of mouse clicks needed. However, I agree with John that it could be time consuming if the drive is large and has 10’s, 100’s, if not 1000's of thousands of files.
It is my opinion that doing it manually through Windows search would be the simplest, fastest, and most efficient. To recap: in the search box, enter the full file name (including the extension). The search result will show the location – full file path. You also have the options to: open the file, open the file location, and copy the file path.
Using “File Explorer” would be my second choice. To recap, the steps would be: 1) open file explorer, 2) make sure the “View” setting is “Details”, 3) in the left column select the “C:\” drive, 4) in the search box (upper right) type the full file name (including the extension). In the resulting list the file path will be shown. The code needed to do it with VBA will be long and complex. I am not familiar with 365 but John is, so it is possible he may put some time into this to create vba code for you. Also, there’s no need to delete the old file. After the “old” file is opened and updated, simply saving the file will save it to the same location with the same name, resulting in no “old” file to delete.
Also, based on what you have said in your question, I don' see the need to use VBA since this will be a one-time event.

Good luck with your quest.

Cheers   :-)
WillieD24 (rep: 587) Aug 10, '24 at 1:44 pm
@Willie - good pointers there for Valentino; nice work! On a VBA solution, I modified some code (I'd used earlier) to get a result for Valentino hopefully.
John_Ru (rep: 6417) Aug 10, '24 at 5:01 pm
Add to Discussion


Answer the Question

You must create an account to use the forum. Create an Account or Login