[唐胡璐]VBS技巧 - Find a File Recursively(递归查找文件)

   '-----------------------------------------------------------------------
  '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 subfolderin objSubFolders                
                  strFullPathToSearch = strRootFolder & "\" & subfolder.name                
                  FindFileRecursively = FindFileRecursively(strFullPathToSearch, strFilename)                
                  If FindFileRecursively <> ""Then                    
                      ExitFor                
                  EndIf            
              Next        
          EndIf    
      EndIf
  EndFunction

posted @ 2013-01-10 08:36  唐胡璐  阅读(415)  评论(0编辑  收藏  举报