+ Reply to Thread
Results 1 to 14 of 14

SubFolder search but for specific file type

Hybrid View

  1. #1
    Registered User
    Join Date
    08-12-2013
    Location
    Denton, Texas
    MS-Off Ver
    Excel 2010
    Posts
    89

    SubFolder search but for specific file type

    Hello,

    I am working with this code snippet. I am very happy with it but I need one small tweak. When I run this code it is going through over 5,000 files and many different sub folders but I really only need it to search for specific file types (mainly Solidworks files .SDDRW & SLDDRW). How would I go about being more specific with my search?

    I did manage to stumble on to this code which seems to narrow down my search to a specific file but I wouldn't really know how to combine the two.

    Any help is greatly appreciated.
    Thank you in advance!

    Sub ProcessAll(sPath As String) 
        Dim Wb As Workbook, sFile As String 
         
        sFile = Dir(sPath & "*.xls") 
         'Loop through all .xls-Files in that path
        Do While sFile <> "" 
             
            Set Wb = Workbooks.Open(sPath & sFile) 
             
             'Do something with that Workbook, insert whatever you want to do here
            Debug.Print Wb.Name 
             'You can save it, if you like, here it's not saved
            Wb.Close False 
             
            sFile = Dir 
        Loop 
    End Sub

    MAIN CODE



    Sub ListFiles()
     
        'Set a reference to Microsoft Scripting Runtime by using
        'Tools > References in the Visual Basic Editor (Alt+F11)
       
        'Declare the variables
        Dim objFSO As Scripting.FileSystemObject
        Dim objTopFolder As Scripting.Folder
        Dim strTopFolderName As String
       
        'Insert the headers for Columns A through B
        Range("A1").Value = "File Name"
        Range("F1").Value = "Path"
       
        'Assign the top folder to a variable
        strTopFolderName = "C:\Users\Domenic\Documents"
       
        'Create an instance of the FileSystemObject
        Set objFSO = CreateObject("Scripting.FileSystemObject")
       
        'Get the top folder
        Set objTopFolder = objFSO.GetFolder(strTopFolderName)
       
        'Call the RecursiveFolder routine
        Call RecursiveFolder(objTopFolder, True)
       
        'Change the width of the columns to achieve the best fit
        Columns.AutoFit
       
    End Sub
     
    Sub RecursiveFolder(objFolder As Scripting.Folder, _
        IncludeSubFolders As Boolean)
     
        'Declare the variables
        Dim objFile As Scripting.File
        Dim objSubFolder As Scripting.Folder
        Dim NextRow As Long
       
        'Find the next available row
        NextRow = Cells(Rows.Count, "A").End(xlUp).Row + 1
       
        'Loop through each file in the folder
        For Each objFile In objFolder.Files
            Cells(NextRow, "A").Value = objFile.Name
            Cells(NextRow, "B").Value = objFile.Path
            NextRow = NextRow + 1
        Next objFile
       
        'Loop through files in the subfolders
        If IncludeSubFolders Then
            For Each objSubFolder In objFolder.SubFolders
                Call RecursiveFolder(objSubFolder, True)
            Next objSubFolder
        End If
       
    End Sub

  2. #2
    Forum Expert
    Join Date
    12-10-2006
    Location
    Sydney
    MS-Off Ver
    Office 365
    Posts
    3,565

    Re: SubFolder search but for specific file type

    Hi there,

    Try this piece of code...

        'Loop through each file in the folder
        For Each objFile In objFolder.Files
            If Right(objFile, 5) = "SDDRW" Or Right(objFile, 5) = "SLDDRW" Then
                Cells(NextRow, "A").Value = objFile.Name
                Cells(NextRow, "B").Value = objFile.Path
                NextRow = NextRow + 1
            End If
        Next objFile
    ...in the relevant spot of the RecursiveFolder macro.

    Regards,

    Robert
    ____________________________________________
    Please ensure you mark your thread as Solved once it is. Click here to see how
    If this post helps, please don't forget to say thanks by clicking the star icon in the bottom left-hand corner of my post

  3. #3
    Valued Forum Contributor
    Join Date
    03-22-2013
    Location
    Australia,NSW, Wirrimbi
    MS-Off Ver
    Excel 2013
    Posts
    1,057

    Re: SubFolder search but for specific file type

    Hi..

    Maybe an alternative method will work for you too?

    This will replace ALL of the code in your initial post..

    Private Sub CommandButton1_Click()
        Dim Z, ZZ, i As Long
        Z = CreateObject("wscript.shell").exec("cmd /c forfiles /P C:\Users\Domenic\Documents /S /M  *.*DDRW  /c ""cmd /c echo  @file ! @path !""").stdout.readall
        ZZ = Split(Replace(Replace(Z, vbCrLf, ""), """", ""),"!")
        For i = 0 To UBound(ZZ) - 1 Step 2
            Range("A" & Range("A" & Rows.Count).End(xlUp).Row).Offset(1).Resize(1, 2).Value = Array(ZZ(i), Left(ZZ(i + 1), InStrRev(ZZ(i + 1), "\")))
        Next i
    End Sub
    NOte: The line in bold is now changed to make it so it ONLY shows the filepath in for subfolders too..
    Last edited by apo; 05-14-2014 at 12:34 AM. Reason: Refined and updated Code..

  4. #4
    Registered User
    Join Date
    08-12-2013
    Location
    Denton, Texas
    MS-Off Ver
    Excel 2010
    Posts
    89

    Re: SubFolder search but for specific file type

    Hey Trebor76,

    Thank you for taking the time to put that together. It worked perfectly, I just had to tweak it from (objFile, 5) to (objFile, 6) and everything populated correctly.

    Apo,

    Thank you for the alternative. Your code gives me a really good insight on how I can achieve what I'm looking to do. I would have never thought to use wscript.shell. Definitely thinking outside the box. Thank you so much. I will play around with it some more.

    Again, thank you both for taking the time to give me something to new to learn. Awesome!

  5. #5
    Valued Forum Contributor
    Join Date
    03-22-2013
    Location
    Australia,NSW, Wirrimbi
    MS-Off Ver
    Excel 2013
    Posts
    1,057

    Re: SubFolder search but for specific file type

    You're welcome..

    I find the Forfiles command is real good for getting specific file values into an array..

    http://technet.microsoft.com/en-us/l.../cc753551.aspx

  6. #6
    Valued Forum Contributor
    Join Date
    03-22-2013
    Location
    Australia,NSW, Wirrimbi
    MS-Off Ver
    Excel 2013
    Posts
    1,057

    Re: SubFolder search but for specific file type

    lol.. I think you just gave me a negative Rep point...

    My Rep went down and there is a Red icon next to your Rep posting in my settings page..

  7. #7
    Registered User
    Join Date
    08-12-2013
    Location
    Denton, Texas
    MS-Off Ver
    Excel 2010
    Posts
    89

    Re: SubFolder search but for specific file type

    Apo,

    Oh no, I'm really sorry. How do I fix it? I'm still rather new to this Forum. I meant to give you a positive.

  8. #8
    Registered User
    Join Date
    08-12-2013
    Location
    Denton, Texas
    MS-Off Ver
    Excel 2010
    Posts
    89

    Re: SubFolder search but for specific file type

    Apo,

    Your code works really really FAST! How is that even possible? Is it because it is being structured into an array? I have to be honest, I was a little scared to run the code because of the wscript.shell (but I jumped on a friends comp and did it haha)

    I really am amazed how insanely fast your code works versus mine. Unfortunately, your code is very complex and I honestly don't know how to wrap my heard around it. Any pointer and I would greatly appreciate it. My guess is because of the array property you have setup in the code but I could be mistaken and unfortunately my handle on arrays has never been good but online there are articles of how arrays can make your program run practically 60X faster.
    Anyways thank you so much and any more advice I would again greatly appreciate it. Also, please let me know how I can reverse the negative mark on your record (if I have to go to admin I will). Very sorry about that (must have checked the wrong radio button because I left a good comment).

  9. #9
    Valued Forum Contributor
    Join Date
    03-22-2013
    Location
    Australia,NSW, Wirrimbi
    MS-Off Ver
    Excel 2013
    Posts
    1,057

    Re: SubFolder search but for specific file type

    Hi..

    Anyways thank you so much and any more advice I would again greatly appreciate it. Also, please let me know how I can reverse the negative mark on your record (if I have to go to admin I will). Very sorry about that (must have checked the wrong radio button because I left a good comment).
    It's all good.. I must be evil.. but it actually gave me a bit of a chuckle.. and to be honest.. everytime i see the little Red 'naughty' icon in the future.. I will probably grin again at the irony of it..

    A good place to start is to enable the Locals Window in the VB Editor (View >Locals Window).. then you will be able to step through the code (using F8) and see what the value of the variables are..

    By using the forfiles command to populate the Array.. it is doing a few things.

    1. Adding values into memory (array) is faster.

    2. Its reducing the amount of values that then need to be looped through after that because ONLY the files that have the correct file extension are returned into the array.
    Remember ... loops are avoided if possible.. but if you have to loop.. at least loop through only what you need to.. as opposed to looping through all files and testing for a condition..

    3. That line is returning the filename AND the filepath and inserting a delimiter (i used the exclamation mark as I thought that would be rarely used in a filename..)

    I'll add some comments in the code below to explain more.. these comments may or may not contain 100% correct info. but it will give you an idea of what i was thinking..

    Private Sub CommandButton1_Click()
        Dim Z, ZZ, i As Long
    
        ' Place All files (filename and filepath)that have *.DDRW file extension in shown filepath into an array.
        ' Add the exclamation mark as a delimiter between each filename and filepath.
        Z = CreateObject("wscript.shell").exec("cmd /c forfiles /P C:\Users\Domenic\Documents /S /M  *.*DDRW  /c ""cmd /c echo  @file ! @path !""").stdout.readall
    
        ' Create a new array from the original array that..
        ' * Replaces the carriage return with 'nothing' (no space).
        ' * Replaces the inverted commas that get returned when using forfiles command with 'nothing' (no space).
        ' * Splits the array using the exclamation mark as the delimiter.
        ZZ = Split(Replace(Replace(Z, vbCrLf, ""), """", ""), "!")
    
        ' Loop through the new array
        ' Step 2 is used to 'tie in' with the next line where i am using Resize to insert the value into the column A AND the adjacent cell in column B.
        For i = 0 To UBound(ZZ) - 1 Step 2
    
        'Insert the Filename and filepath into column A and B.
        ' Left and InStrRev are used for the value in Column B (file path)to find the last backslash in the file path and only use the string to the left of it..
            Range("A" & Range("A" & Rows.Count).End(xlUp).Row).Offset(1).Resize(1, 2).Value = Array(ZZ(i), Left(ZZ(i + 1), InStrRev(ZZ(i + 1), "\")))
        Next i
    End Sub
    Hope that makes more sense?
    Last edited by apo; 05-14-2014 at 07:46 PM.

  10. #10
    Registered User
    Join Date
    08-12-2013
    Location
    Denton, Texas
    MS-Off Ver
    Excel 2010
    Posts
    89

    Re: SubFolder search but for specific file type

    Hey apo,

    I had recently found a comparison you did with forfiles vs Dir on another Forum. Could you please show me how I could use that to speed up the method you used when you introduce me to the Forfiles on here.

    Private Sub CommandButton1_Click() 
         'Dir version
        Dim x, fldr As FileDialog, SelFold As String, i As Long 
        Set fldr = Application.FileDialog(msoFileDialogFolderPicker) 
        With fldr 
            .Title = "Select a Folder" 
            If .Show <> -1 Then Exit Sub 
            SelFold = .SelectedItems(1) 
        End With 
        x = Split(CreateObject("wscript.shell").exec("cmd /c Dir """ & SelFold & "\*.*"" /s/b").stdout.readall, vbCrLf) 
        Cells(1, 1).Resize(UBound(x)).Value = Application.Transpose(x) 
         
        For i = 1 To Sheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row 
            Cells(i, 1) = Split(Cells(i, 1), "\")(UBound(Split(Cells(i, 1), "\"))) 
        Next i 
        MsgBox "Done!" 
    End Sub

  11. #11
    Registered User
    Join Date
    08-12-2013
    Location
    Denton, Texas
    MS-Off Ver
    Excel 2010
    Posts
    89

    Re: SubFolder search but for specific file type

    Apo,

    This definitely explains a lot. Obviously I'm still going to need to sit down and really try and dissect every line of this code (I'll see how much my ego can take after many failures but it really is the best teacher haha).

    There are two questions I had when attempting a few things.

    1) When I run the code on Windows using my Mac (Windows 7 is on parallels) my directory is "\\psf\User\Desktop" and the code doesn't work. Mainly just flashes the cmd and thats it. I was wondering if it has to do with the director? I ran the code at work on a server and it managed to work on unprotected files. I wonder if I'm missing something.

    2) I had attempted to look for two different files by using this method *.*SLDDRW & *.*SLDPRT but I knew it was a long shot and obviously it didn't work. I was hoping you could enlighten me on how to add search for multiple files.

    Again, thank you for all your help. This website http://technet.microsoft.com/en-us/l.../cc753551.aspx has diffidently open my eyes to another side of VBA.

  12. #12
    Valued Forum Contributor
    Join Date
    03-22-2013
    Location
    Australia,NSW, Wirrimbi
    MS-Off Ver
    Excel 2013
    Posts
    1,057

    Re: SubFolder search but for specific file type

    HI.. I remember you.. the 'negative Rep point guy',lol..

    It's Friday night here.. had a couple of cold ones.. but I think this is what you want?
    Private Sub CommandButton1_Click()
        Dim x, fldr As FileDialog, SelFold As String, i As Long
        Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
        With fldr
            .Title = "Select a Folder"
            If .Show <> -1 Then Exit Sub
            SelFold = .SelectedItems(1)
        End With
        x = Split(CreateObject("wscript.shell").exec("cmd /c Dir """ & SelFold & "\*.*DDRW"" /s/b").stdout.readall, vbCrLf)
        Cells(1, 1).Resize(UBound(x)).Value = Application.Transpose(x)
    
        For i = 1 To Sheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
            Cells(i, 2) = Split(Cells(i, 1), "\")(UBound(Split(Cells(i, 1), "\")))
            Cells(i, 1) = Left(Cells(i, 1), InStrRev(Cells(i, 1), "\"))
        Next i
        MsgBox "Done!"
    End Sub

  13. #13
    Registered User
    Join Date
    08-12-2013
    Location
    Denton, Texas
    MS-Off Ver
    Excel 2010
    Posts
    89

    Re: SubFolder search but for specific file type

    HAHA yeah that's me, the negative rep guy, good memory.. It's Friday morning here, I can't wait to take down a couple of cold ones tonight!
    I just did a quick run on the code, it looks good. I will need to play around with it when I have more time but was so excited I had to run it now ha-ha.

    P.S is there a monetary way I can repay on this site? Your methods have helped me tremendously. I have used Forfiles for several things now and have been studying up on technet.microsoft. Such a good source!

    Thanks again!

  14. #14
    Valued Forum Contributor
    Join Date
    03-22-2013
    Location
    Australia,NSW, Wirrimbi
    MS-Off Ver
    Excel 2013
    Posts
    1,057

    Re: SubFolder search but for specific file type

    Sounds good..

    There might be a way for you to Donate to the running costs of this site.. not sure.. best to PM a Mod or Admin to find out how..

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. VBA code needed to move from Outlook 2010 subfolder to Symantec Vault subfolder
    By Marijke in forum Outlook Programming / VBA / Macros
    Replies: 1
    Last Post: 01-09-2014, 12:14 PM
  2. To have flexibility to open workbook file on a specific drive\subfolder.
    By anneypng in forum Excel Programming / VBA / Macros
    Replies: 3
    Last Post: 10-02-2012, 01:30 AM
  3. Moving an e-mail from a subfolder in Mailbox to the equivalent subfolder in an archive PST
    By johncassell in forum Outlook Programming / VBA / Macros
    Replies: 0
    Last Post: 07-09-2012, 11:31 AM
  4. Subfolder Search
    By kreshnr in forum Excel Programming / VBA / Macros
    Replies: 8
    Last Post: 02-25-2009, 09:49 AM
  5. [SOLVED] How to select a specific file type
    By MervB in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 11-04-2005, 04:10 AM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1