Share via


The Basics of File Searching

This content is no longer actively maintained. It is provided as is, for anyone who may still be using these technologies, with no warranties or claims of accuracy with regard to the most recent product version or service release.

The following code fragment illustrates how to use an application's FileSearch property to return a reference to the FileSearch object. Because the FileSearch object is shared among all Microsoft® Office applications, this code will work without modification from within any Office application:

Function FindFile(strFileSpec As String)
   Dim fsoFileSearch As FileSearch
   
   
   
   Set fsoFileSearch = Application.FileSearch
   With fsoFileSearch
      .NewSearch
      .LookIn = "c:\"
      .FileName = strFileSpec
      .SearchSubFolders = False
      If .Execute() > 0 Then
         For Each varFile In .FoundFiles
            strFileList = strFileList & varFile & vbCrLf
         Next varFile
      End If
   End With
   MsgBox strFileList
   
   
   
End Function

The FileSearch object has two methods and several properties you can use to build custom file-searching functionality into your custom Office applications. The previous example uses the NewSearch method to clear any previous search criteria and the Execute method to carry out the search for the specified files. The Execute method returns the number of files found, and also supports optional parameters that make it possible for you specify the sort order, the sort type, and whether to use only saved Fast Find indexes to perform the search. You use the FoundFiles property to return a reference to the FoundFiles object that contains the names of all matching files found in your search.

Note   You must use the NewSearch method to clear any search criteria from previous searches; otherwise, the new search criteria will be added to the existing search criteria.

You use the LookIn property to specify what directory to begin searching in and the SearchSubFolders property to specify whether the search should extend to subfolders of the directory specified in the LookIn property. The FileName property supports wildcard characters and a semicolon-delimited list of file names or file-type specifications.

For more information about using the methods and properties of the FileSearch object, search the Microsoft Office Visual Basic Reference Help index for "FileSearch object."

See Also

Working with Shared Office Components | Working with the FileSearch Object | Using Advanced File-Searching Features | Creating Reusable File-Search Code