Find a File Recursively(递归查找文件)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
'-----------------------------------------------------------------------
  'Function: FindFileRecursively
  'Finds the first instance of a file within the root folder or one of its subfolders
  '
  'Remarks:
  '   Uses recursion
  '
  'Arguments
  '   ByVal strRootFolder - As String (absolute folder)
  '   ByVal strFilename - As String
  '
  'Returns:
  '   String with full file pathname based on root folder and file name
  '
  'Owner:
  '
  'Date:
  '
  '-----------------------------------------------------------------------    
   PublicFunction FindFileRecursively(ByVal strRootFolder, ByVal strFilename)
      Dim FSO    
      Dim strFullPathToSearch    
      Dim objSubFolders, subfolder    
   
      Set FSO = CreateObject("Scripting.FileSystemObject")    
      'Initialize function    
      FindFileRecursively = ""    
      'Check that filename is not empty    
      If strFileName = ""ThenExitFunction    
      'Get full file pathname    
      strFullPathToSearch = strRootFolder & "\" & strFilename    
      'Check if root folder exists    
      If FSO.FolderExists(strRootFolder) Then        
          'Check if file exists under root folder        
          If FSO.FileExists(strFullPathToSearch) Then            
              FindFileRecursively = strFullPathToSearch        
          Else            
              'Get subfolders            
              Set objSubFolders = FSO.GetFolder(strRootFolder).SubFolders            
              ForEach subfolder in objSubFolders                
                  strFullPathToSearch = strRootFolder & "\" & subfolder.name                
                  FindFileRecursively = FindFileRecursively(strFullPathToSearch, strFilename)                
                  If FindFileRecursively <> ""Then                    
                      ExitFor                
                  EndIf            
              Next        
          EndIf    
      EndIf
  EndFunction
唐胡璐 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
分享创造价值,您的支持将鼓励我继续前行!