Apply existing VBS folder search to sub folders?

前端 未结 2 1538
一个人的身影
一个人的身影 2021-01-28 02:38

I am using the following code to search a folder for a file name, open the file run an excel macro, save the file, and close. I would like to extend this to loop through sub fol

2条回答
  •  滥情空心
    2021-01-28 02:48

    Steps towards the solution:

    1. Create the following method:

      Sub IterateFolder(dir, fso)
        For Each file In fso.GetFolder(dir).Files
          If InStr(file.Name, "OPS") > 0 Then
            RunMacroAndSaveAs file, "Main"
          ElseIf InStr(file.Name, "Event") > 0 Then
            RunMacroAndSaveAs file, "Events"
          End If
        Next
      End Sub`
      

    and call it like this: IterateFolder "C:\Users\ntunstall\Desktop\test", fso

    This will still do this for the first level, but do this as a first step and understand it.

    1. Understand fso.SubFolders

    2. Apply the new knowledge:

      Sub IterateFolder(dir, fso)
        For Each file In fso.GetFolder(dir).Files
          If InStr(file.Name, "OPS") > 0 Then
            RunMacroAndSaveAs file, "Main"
          ElseIf InStr(file.Name, "Event") > 0 Then
            RunMacroAndSaveAs file, "Events"
          End If
        Next
        For Each sf In fso.SubFolders
          IterateFolder sf, fso
        Next
      End Sub
      

    I do not work with VBScript, therefore I am not 100% sure if I'm right. If you have any problems with the solution, please ask.

    EDIT:

    As pointed out in the commenting section, fso is a variable which was out of scope in the Sub. I have edited my answer to make sure it is passed.

    EDIT2:

    Let's hope this is the coup de grace. I was mistaken in the way subfolders were iterated. Change this chunk:

    For Each sf In fso.SubFolders
      IterateFolder sf, fso
    Next
    

    to this:

    For Each sf In fso.GetFolder(dir).SubFolders
      IterateFolder sf, fso
    Next
    

    EDIT3:

    We need to check SubFolders against null. According to this source, we should change this:

    For Each sf In fso.GetFolder(dir).SubFolders
      IterateFolder sf, fso
    Next
    

    to this:

    If Not IsNull(fso.GetFolder(dir).SubFolders) Then
      For Each sf In fso.GetFolder(dir).SubFolders
        IterateFolder sf, fso
      Next
    End If
    

提交回复
热议问题