本类文章的标签为 ‘FileSearch对象’


使用VBA操作文件(11):处理文件、文件夹和驱动器的VBA技术和技巧

1 颗星2 颗星3 颗星4 颗星5 颗星 (1 人投票, 平均: 5.00 out of 5)
Loading ... Loading ...

如果希望处理文件或文件系统,有几种选择可用。最好的选择取决于您希望完成什么任务。可用的选择包括使用VBA函数、Microsoft Scripting Runtime对象库、FileSearch对象,以及与文件系统相关的Windows API函数。
使用VBA函数
可以使用许多VBA函数处理文件系统,下表对这些函数进行了总结。

VBA函数或语句 说明
Dir 返回与指定的格式或文件属性相匹配的文件、目录或文件夹的名称。
GetAttr 返回文件、目录或文件夹的属性。
SetAttr 指定文件、目录或文件夹的属性。
CurDir 返回当前目录。
ChDir 修改当前目录。
ChDrive 修改当前驱动器。
MkDir 创建一个新目录。
RmDir 移除一个现有的目录。
Kill 删除一个或多个文件。
FileLen 以字节返回磁盘中文件的长度。
LOF 以字节返回一个打开文件的长度。
FileCopy 复制磁盘中的文件。
FileDateTime 返回文件创建或最后修改的日期和时间。
Name 重命名文件并将其移动到磁盘中另一个位置。
Open 打开磁盘中的文件来读取或写入。
Input 从打开的文件中读取字符。
Print 写文本到顺序文件中。
Write 写文本到顺序文件中。
Close 关闭使用Open语句打开的文件。


如何使用Dir函数判断某文件是否存在?
Dir函数返回在pathname参数中指定的文件的名称。通常使用Dir函数来判断是否指定的文件存在,例如下面的DoesFileExist函数:

Function DoesFileExist(strFileSpec As String) As Boolean
    ' 如果参数strFileSpec指定的文件存在则返回True.
    ' 如果strFileSpec不是有效的文件或者是一个目录则返回False.
    Const INVALID_ARGUMENT As Long = 53
    On Error GoTo DoesfileExist_Err
    If (GetAttr(strFileSpec) And vbDirectory) <> vbDirectory Then
        DoesFileExist = CBool(Len(Dir(strFileSpec)) > 0)
    Else
        DoesFileExist = False
    End If
DoesfileExist_End:
    Exit Function
DoesfileExist_Err:
    DoesFileExist = False
    Resume DoesfileExist_End
End Function

本例中,GetAttr函数用于确保strFileSpec参数中的值不是一个目录。这是因为,如果向Dir函数中传递一个有效的目录名称,那么将返回在该目录中找到的第一个文件。
如何使用Dir函数获取文件夹中所有文件的名称?
如果pathname参数包含文件夹的路径而不是文件夹中某文件的名称,那么Dir函数返回在该文件夹中找到的第一个文件的名称。接着,再调用Dir函数而无需任何参数,获取文件夹中后面每一个文件的名称。例如,下面的过程返回一个数组,包含在strDirPath参数中指定的目录内所有文件的名称:

Function GetAllFilesInDir(ByVal strDirPath As String) As Variant
    ' 遍历strDirPath中指定的目录并在数组中保存每个文件名
   ' 然后返回该数组到调用过程.
    ' 如果strDirPath不是一个有效的目录则返回False.
    Dim strTempName As String
    Dim varFiles() As Variant
    Dim lngFileCount As Long
 
    On Error GoTo GetAllFiles_Err
 
    ' 确保strDirPath以"\"字符结尾.
    If Right$(strDirPath, 1) <> "\" Then
        strDirPath = strDirPath & "\"
    End If
 
    ' 确保strDirPath是一个目录.
    If GetAttr(strDirPath) = vbDirectory Then
        strTempName = Dir(strDirPath, vbDirectory)
        Do Until Len(strTempName) = 0
            ' 排除 ".", "..".
            If (strTempName <> ".") And (strTempName <> "..") Then
                ' 确保没有子目录名称.
                If (GetAttr(strDirPath & strTempName) _
                    And vbDirectory) <> vbDirectory Then
                    ' 增加数组的大小以适应发现的文件名并将其添加到数组.
                    ReDim Preserve varFiles(lngFileCount)
                    varFiles(lngFileCount) = strTempName
                    lngFileCount = lngFileCount + 1
                End If
            End If
            ' 使用Dir函数查找下一个文件名.
            strTempName = Dir()
        Loop
        ' 返回包含已找到的文件名称的数组.
        GetAllFilesInDir = varFiles
    End If
GetAllFiles_End:
    Exit Function
GetAllFiles_Err:
    GetAllFilesInDir = False
    Resume GetAllFiles_End
End Function

GetAllFilesInDir函数通过遍历目录中的每一项,并且对于发现的文件,将其名称添加到数组。第一次调用Dir时,使用目录名作为其参数。每增加一次调用都使用不带参数的Dir函数。该过程使用GetAttr函数来确保strDirPath参数包含一个有效的目录,也避免任何子目录的名称被添加到数组中。注意,该过程筛选出“.”和“..”,代表当前目录和父目录。
可以使用下面的过程测试GetAllFilesInDir过程。可以对strDirName参数试不同的值,然后使用F8逐行运行代码,看该过程是如何工作的。

Sub TestGetAllFiles()
    Dim varFileArray As Variant
    Dim lngI As Long
    Dim strDirName As String
 
    Const NO_FILES_IN_DIR As Long = 9
    Const INVALID_DIR As Long = 13
 
    On Error GoTo Test_Err
 
    strDirName = "c:\my documents"
    varFileArray = GetAllFilesInDir(strDirName)
    For lngI = 0 To UBound(varFileArray)
        Debug.Print varFileArray(lngI)
    Next lngI
 
Test_Err:
    Select Case Err.Number
        Case NO_FILES_IN_DIR
            MsgBox "The directory named '" & strDirName _
                & "' contains no files."
        Case INVALID_DIR
            MsgBox "'" & strDirName & "' is not a valid directory."
        Case 0
        Case Else
            MsgBox "Error #" & Err.Number & " - " & Err.Description
    End Select
End Sub

使用Microsoft Scripting Runtime Object Library
Microsoft Scripting Runtime对象库包含可以用于操作文件和目录的对象,并且比前面讲述的VBA函数更容易使用。
在使用该对象库之前,必须设置对该对象库的引用。如果在“引用”对话框中没有找到该对象库,那么应该可以在C:\Windows\System子文件夹中找到它(Scrrun.dll)。
下表描述了Scripting Runtime对象库是的对象。

对象 集合 描述
Dictionary 顶层对象,与VBA Collection集合对象相似。
Drive Drives 引用系统中的驱动器或驱动器的集合。
File Files 引用文件系统中的文件或文件集合。
FileSystemObject 顶层对象,用于访问驱动器、文件夹、文件。
Folder Folders 引用文件系统中的文件夹或文件夹集合。
TextStream 引用读取、写入或追加到文本文件中的一系列文本。


在Scripting Runtime对象库中的顶层对象是Dictionary对象和FileSystemObject对象。要使用Dictionary对象,则需创建一个Dictionary类型的对象变量,然后设置其为Dictionary对象的新实例。

Dim dctDict As Scripting.Dictionary
Set dctDict = New Scripting.Dictionary

要在代码中使用Scripting Runtime库中的其它对象,必须首先创建FileSystemObject类型的变量,然后使用New关键词创建该FileSystemObject对象的新实例,如下面的代码所示:

Dim fsoSysObj As Scripting.FileSystemObject
Set fsoSysObj = New Scripting.FileSystemObject

接着使用这个引用FileSystemObject对象的变量来处理Drive、Folder、File和TextStream对象。
如何使用FileSystemObject对象来处理文件和文件夹?
一旦创建了FileSystemObject对象的新实例,就能够使用它来处理驱动器、文件夹和文件了。
下面的过程返回特定文件夹中的文件到Dictionary对象里。GetFiles过程接受三个参数:目录路径、Dictionary对象、一个可选的布尔参数,指定是否应该递归调用该过程。该过程返回一个布尔值,指明是否过程运行成功。
该过程首先使用GetFolder方法返回对Folder对象的引用,然后遍历该文件夹的Files集合,添加每个文件的文件名称和路径到Dictionary对象中。如果blnRecursive参数设置为True,那么GetFiles过程被递归调用以返回每个子文件夹中的文件。

Function GetFiles(strPath As String, _
                dctDict As Scripting.Dictionary, _
                Optional blnRecursive As Boolean) As Boolean
 
   ' 本过程返回目录中的所有文件到Dictionary对象中.
   ' 如果递归调用则同时返回子文件夹中的所有文件.
   
   Dim fsoSysObj      As Scripting.FileSystemObject
   Dim fdrFolder      As Scripting.Folder
   Dim fdrSubFolder   As Scripting.Folder
   Dim filFile        As Scripting.File
 
   ' 返回新的FileSystemObject.
   Set fsoSysObj = New Scripting.FileSystemObject
 
   On Error Resume Next
   ' 获取文件夹.
   Set fdrFolder = fsoSysObj.GetFolder(strPath)
   If Err <> 0 Then
      ' 不正确的路径.
      GetFiles = False
      GoTo GetFiles_End
   End If
   On Error GoTo 0
 
   ' 遍历Files集合,添加到字典.
   For Each filFile In fdrFolder.Files
      dctDict.Add filFile.Path, filFile.Path
   Next filFile
 
   ' 如果Recursive标志为真,则递归调用.
   If blnRecursive Then
      For Each fdrSubFolder In fdrFolder.SubFolders
         GetFiles fdrSubFolder.Path, dctDict, True
      Next fdrSubFolder
   End If
 
   ' 如果没有错误发生则返回True.
   GetFiles = True
 
GetFiles_End:
   Exit Function
End Function
 
   ' 如果没有错误发生则返回True.
   GetFiles = True
 
GetFiles_End:
   Exit Function
End Function

可以使用下面的过程来测试GetFiles过程。该过程创建一个新Dictionary对象,将其传递到GetFiles过程,然后在立即窗口中打印在strDirPath目录及其子目录中的每个文件。

Sub TestGetFiles()
   ' 测试GetFiles函数.

   Dim dctDict As Scripting.Dictionary
   Dim varItem As Variant
   Dim strDirPath As String
 
   strDirPath = "c:\my documents\"
   ' 创建新的字典.
   Set dctDict = New Scripting.Dictionary
   ' 递归调用, 返回文件到Dictionary对象.
   If GetFiles(strDirPath, dctDict, True) Then
      ' 打印字典中的项目.
      For Each varItem In dctDict
         Debug.Print varItem
      Next
   End If
End Sub

可以对strDirPath参数试验不同的值,看看该过程是如何工作的。
如何使用FileSystemObject来处理文件属性?
File对象和Folder对象提供了Attributes属性,可用来读取或设置文件或文件夹的属性,如下面的示例。
ChangeFileAttributes过程接受四个参数:文件夹的路径、指定要设置的属性的可选的常量、指定要移除的属性的可选常量、指定是否递归调用过程的可选的参数。
如果传递的文件夹路径是有效的,那么该过程返回Folder对象。接着检查是否提供了lngSetAttr参数,如果是,那么该过程遍历文件夹中的所有文件,追加新的属性到每个文件现有的属性中。对于lngRemoveAttr参数做同样的事情,在本例中,如果指定的属性存在于集合中的文件内则移除。
最后,该过程检查blnRecursive参数是否被设置为True,如果是则为strPath参数指定的每个子文件夹中的每个文件调用该过程。

Function ChangeFileAttributes(strPath As String, _
                            Optional lngSetAttr As FileAttribute, _
                            Optional lngRemoveAttr As FileAttribute, _
                            Optional blnRecursive As Boolean) As Boolean
 
   ' 本函数接受一个目录路径, 一个指定文件属性设置的值
   ' 一个指定文件属性移除的值
   ' 一个指明是否递归调用的标志
   ' 如果没有发生错误则返回True.
   
   Dim fsoSysObj      As Scripting.FileSystemObject
   Dim fdrFolder      As Scripting.Folder
   Dim fdrSubFolder   As Scripting.Folder
   Dim filFile        As Scripting.File
 
   ' 返回新的FileSystemObject.
   Set fsoSysObj = New Scripting.FileSystemObject
 
   On Error Resume Next
   ' 获取文件夹.
   Set fdrFolder = fsoSysObj.GetFolder(strPath)
   If Err <> 0 Then
      ' 不正确的路径.
      ChangeFileAttributes = False
      GoTo ChangeFileAttributes_End
   End If
   On Error GoTo 0
 
   ' 如果调用者传递属性去设置则设置所有的.
   If lngSetAttr Then
      For Each filFile In fdrFolder.Files
         If Not (filFile.Attributes And lngSetAttr) Then
            filFile.Attributes = filFile.Attributes Or lngSetAttr
         End If
      Next
   End If
 
   ' 如果调用者传递属性去移除则移除所有的.
   If lngRemoveAttr Then
      For Each filFile In fdrFolder.Files
         If (filFile.Attributes And lngRemoveAttr) Then
            filFile.Attributes = filFile.Attributes - lngRemoveAttr
         End If
      Next
   End If
 
   ' 如果调用者设置blnRecursive参数为True,则递归调用函数.
   If blnRecursive Then
      ' 遍历子文件夹.
      For Each fdrSubFolder In fdrFolder.SubFolders
         ' 调用带有子文件夹路径的函数.
         ChangeFileAttributes fdrSubFolder.Path, lngSetAttr, _
            lngRemoveAttr, True
      Next
   End If
   ChangeFileAttributes = True
 
ChangeFileAttributes_End:
   Exit Function
End Function

可以使用下面的过程测试ChangeFileAttributes过程。在本例中,具有隐藏属性设置的“我的文档”文件夹中的所有文件被设置可见:

Sub TestChangeAttributes()
    If ChangeFileAttributes("c:\my documents", , _
        Hidden, False) = True Then
        MsgBox "File attributes succesfully changed!"
    End If
End Sub

可以对ChangefileAttributes过程中的参数试验不同的值,看看该过程是如何工作的。
使用FileSearch对象
FileSearch对象是Microsoft Office 9.0 Object Library中的一个成员,公开了Office文件打开对话框的所有功能的编程接口,包括在高级查找对话框中的功能。可以使用FileSearch对象的对象、方法和属性基于提供的条件来搜索文件或文件集合。
下面的示例展示了如何使用FileSearch驿象查找在strFilespec参数中指定类型的一个和多个文件。注意,通过分号分隔符指定扩展名列表可以搜索多个文件扩展名:

Function CustomFindFile(strFileSpec As String)
    ' 本过程演示一个简单的文件搜索程序
    ' 显示一个消息框,包含在"C:\"目录中与参数strFileSpec提供的文件规范相匹配的所有文件的名称
    ' 参数strFileSpec可以包含一个或多个在分号分隔列表中的文件规格.
    ' 例如,下面的strFileSpec参数返回"c:\"中包含扩展名"*.log;*.bat;*.ini"的包有文件
    
   Dim fsoFileSearch   As Office.FileSearch
    Dim varFile         As Variant
    Dim strFileList     As String
 
    ' 如果输入有效,那么处理文件搜索.
    If Len(strFileSpec) >= 3 And InStr(strFileSpec, "*.") > 0 Then
        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
    Else
        MsgBox strFileSpec & " is not a valid file specification."
        Exit Function
    End If
End Function

FileSearch对象有两个方法和一些属性,可用于在自定义的Office解决方案中创建自定义文件搜索功能。上述示例使用NewSearch方法清除任何以前的搜索条件,Execute方法执行搜索特定的文件。Execute方法返回找到的文件数,同时支持可选的参数来指定排序顺序、排序类型、以及是否用来仅保存快速搜索索引来执行搜索。使用FoundFiles属性返回对FoundFiles对象的引用(FoundFiles对象包含搜索中找到的所有匹配文件的名称)。
使用LookIn属性指定搜索的目录,使用SearchSubFolders属性指定是否搜索在LookIn属性指定的目录中的子文件夹。FileName属性支持通配符和文件名或文件类型规范的分号分隔列表。

注:本文初译自MSDN:Working with Files, Folders, and Drives: More VBA Tips and Tricks,辑录于此,作为文件操作应用大全的一部分。

相关文章

使用VBA操作文件(10):SearchFolders集合

1 颗星2 颗星3 颗星4 颗星5 颗星 (目前还没有人投票)
Loading ... Loading ...

本文主要介绍如何使用SearchFolders集合搜索文件。
介绍
在Office 9.0类型库中的FileSearch对象允许编程搜索匹配条件(例如作者的名字、文件的类型、最后修改文件的日期,等)的文件。此外,可以缩小搜索条件到已知的文件夹及任何子文件夹。然而,如果不知道路径的话,就没有方法搜索文件夹。
在Office 10.0类型库中添加到FileSearch对象的SearchFolders集合允许编程搜索多个文件夹中的文件,即便不知道它们的路径。
探索创建搜索条件的对象模型
为了更好地理解如何编程创建搜索条件,下图显示了可以使用的各种集合和对象,下表描述了SearchFolders集合及其子对象的用途。
filesearchobjectmodel1
图:FileSearch对象模型
表:SearchFolders集合及其子对象

对象/集合 用途
SearchFolders 代表要通过使用FileSearch对象搜索的文件夹集合。每个应用程序仅有一个SearchFolders集合。可以添加一个或多个ScopeFolder对象到该SearchFolders集合。
ScopeFolder 代表希望添加到搜索的文件夹或子文件夹。每个ScopeFolder对象可以包含0个或多个ScopeFolders对象(子文件夹的集合)。如果ScopeFolder对象没有相应的子ScopeFolder对象的ScopeFolders集合,意味着该文件夹没有子文件夹(但该文件夹可以包含文件)。
ScopeFolders 代表属于父ScopeFolder对象的一个或多个子文件夹的集合。


其它搜索对象简介

  • FileTypes集合 (Office XP中新增) 代表能够搜索的一个或多个文件类型(例如,Microsoft Excel文件或Microsoft PowerPoint文件)。在一个应用程序中仅有一个FileTypes集合。调用FileSearch对象的NewSearch方法清除FileTypes集合中任何以前的设置(例如,Application.FileSearch.NewSearch)。
  • FoundFiles集合 代表文件搜索返回的0个或多个文件。可以使用For Each…Next循环与FoundFiles集合一起,对查找的每个文件采取某种操作,例如打开或打印。等价于搜索结果任务窗格中呈现的文件列表。调用FileSearch对象的Execute方法开始文件搜索,更新FoundFiles集合(例如,Application.FileSearch.Execute)。
  • PropertyTests集合 代表应用到基本搜索的一个或多个高级搜索条件。等价于在高级搜索任务窗格的搜索区中呈现的结果。
  • SearchScopes集合(Office XP新增) 代表可以搜索的可用的本地或网络计算机资源 (例如,我的电脑,网上邻居,或Microsoft Outlook)。不能够从SearchScopes集合中添加或删除SearchScope对象等价于选择搜索任务窗格中的搜索框。

示例:搜索文件夹中包含指定文本的文件
示例下载:

本示例演示了SearchFolders集合如何工作。在示例中,当用户选择Word文档中的一些文本,并通过自定义用户窗体提供文件夹名后,代码搜索用户计算机中与用户提供的文件夹名相匹配的包含所选文本的任何文件,然后使用自定义用户窗体报告匹配文件的列表。
在搜索之前,应该清除任何以前的搜索条件。ClearPreviousSearchFolders过程通过从SearchFolders中移除任何存在的SearchFolder对象来完成这项操作。此外,该过程设置LookIn属性为空字符串,并调用NewSearch方法重设所有剩余的搜索条件为其默认设置。
为了搜索用户计算机上所有的文件夹,使用了递归的SearchForSubFolders过程。如果没有这个过程,那么搜索条件将仅限于用户计算机上文件夹的第一层。SearchForSubFolders过程调用其本身多次以遍历计算机整个目录结构。每次该过程找到与用户提供的文件夹名称相匹配的文件夹名后,调用AddToSearchFolders方法添加文件夹到应用程序的SearchFolders集合。
遍历用户计算机的整个目录结构之后,通过SearchFolders集合搜索包含用户所选文本的任何文件。FileSearch对象的Execute方法,与PropertyTests集合的LookIn属性和Add方法一起,返回包含相匹配文件的FoundFiles集合,通过调用ReportResultsToUser过程来更新和显示用户窗体报告给用户。
小结
SearchFolders集合允许编程搜索多个文件夹中的文件,即便事先不知道其路径。因为SearchFolders集合是FileSearch对象的一部分,可以容易地合并其它搜索条件到搜索解决方案中。

注:本文初译自MSDN:Using the SearchFolders Collection,收录于此,作为文件操作大全的一部分。

相关文章

使用VBA操作文件(1):使用Excel对话框

1 颗星2 颗星3 颗星4 颗星5 颗星 (2 人投票, 平均: 5.00 out of 5)
Loading ... Loading ...

本专题主要讲述使用VBA操作文件和文件夹的相关知识,尽量不涉及对文件中具体内容的操作。如何操作文件中具体内容的知识,将在后续内容外部数据操作中作详细介绍。
Excel VBA提供了一些方法和对象,能够调用Excel内置对话框来进行文件操作。
 GetOpenFilename方法
使用GetOpenFilename方法能够获得有效的文件名,包括该文件的完整路径。此时,将显示标准的“打开”对话框,但并不真正打开指定的文件,而是返回包含用户所选文件的文件名和路径的字符串。其语法如下:

object.GetOpenFilename (FileFilter,FilterIndex,Title,ButtonText,MultiSelect)

所有参数均可选。其中,参数FileFilter代表指定文件筛选条件的字符串,即确定出现在在“打开”对话框中“文件类型”下拉列表中的内容,由文件筛选字符串和通配符表示的文件筛选规则说明组成,其中每一部分和每一对都用逗号隔开。如果省略,则该参数的的默认值为:

"All Files (*.*),*.*"

该字符串的第一部分(All Files (*.*))是显示在“文件类型”下拉列表中的文本,第二部分(*.*)实际上确定要显示哪些文件。
下面的指令将一个字符串赋值给名为Filt的变量,然后可以用作GetOpenFilename方法的参数FileFilter的值。

Filt = "Text Files (*.txt),*.txt," & _
         "Lotus Files (*.prn),*.prn," & _
         "Comma Separated Files (*.csv),*.csv," & _
         "ASCII Files (*.asc),*.asc," & _
         "All Files (*.*),*.*"

此时,“打开”对话框允许用户从5种文件类型中选择。
提示:使用换行符将长语句分成多行,有助于代码阅读。
参数FilterIndex代表默认的文件筛选条件的索引号,用于指定在“文件类型”框中显示的文件类型。
参数Title代表对话框的标题,如果省略该参数,则标题为“打开”。
参数ButtonText只用于Macintosh机。
参数MultiSelect用于指定是否能够选择多个文件名,如果为True则能够选中多个文件名,所有这些文件将返回到一个数组中。默认值为False。

Sub GetImportFileName()
    Dim Filt As String
    Dim FilterIndex As Integer
    Dim Title As String
    Dim FileName As Variant
 
    '创建文件筛选列表
    Filt = "Text Files (*.txt),*.txt," & _
         "Lotus Files (*.prn),*.prn," & _
         "Comma Separated Files (*.csv),*.csv," & _
         "ASCII Files (*.asc),*.asc," & _
         "All Files (*.*),*.*"
 
    '默认显示*.*
    FilterIndex = 5
 
    '设置对话框标题
    Title = "Select a File to Import"
 
    '获取文件名
    FileName = Application.GetOpenFilename _
        (FileFilter:=Filt, _
         FilterIndex:=FilterIndex, _
         Title:=Title)
 
    '如果取消对话框则退出
    If FileName = False Then
        MsgBox "No file was selected."
        Exit Sub
    End If
 
    '显示文件的完整路径和名称
    MsgBox "You Selected " & FileName
End Sub

下面的代码与上述代码类似,区别在于用户可以按Ctrl键或者Shift键选择多个文件。

Sub GetImportFileName2()
    Dim Filt As String
    Dim FilterIndex As Integer
    Dim Title As String
    Dim FileName As Variant
    Dim i As Integer
    Dim Msg As String
 
    '创建文件筛选列表
    Filt = "Text Files (*.txt),*.txt," & _
         "Lotus Files (*.prn),*.prn," & _
         "Comma Separated Files (*.csv),*.csv," & _
         "ASCII Files (*.asc),*.asc," & _
         "All Files (*.*),*.*"
 
    '默认显示*.*
    FilterIndex = 5
 
    '设置对话框标题
    Title = "Select a File to Import"
 
    '获取文件名
    FileName = Application.GetOpenFilename _
        (FileFilter:=Filt, _
         FilterIndex:=FilterIndex, _
         Title:=Title, _
         MultiSelect:=True)
 
    '如果取消对话框则退出
    If Not IsArray(FileName) Then
        MsgBox "No file was selected."
        Exit Sub
    End If
 
    '显示文件的完整路径和名称
    For i = LBound(FileName) To UBound(FileName)
        Msg = Msg & FileName(i) & vbCrLf
    Next i
    MsgBox "You Selected: " & vbCrLf & Msg
End Sub

此时,变量FileName是一个数组。该过程通过判断FileName变量是否是数组,检测用户是否单击了“取消”按钮。如果没有单击“取消”按钮,那么结果至少是由一个元素组成的数组。
GetSaveAsFilename方法
GetSaveAsFilename方法与GetOpenFilename方法类似,但它显示的是“另存为”对话框,允许用户选择或者指定某文件。该方法返回一个文件名及其路径,但不会发生任何动作。其语法为:

object.GetSaveAsFilename (InitialFilename,FileFilter,FilterIndex,Title,ButtonText)

所有参数均为可选参数。其中,参数InitialFilename指定希望使用的文件名称;参数FileFilter是指定文件筛选条件的字符串;FilterIndex指定默认文件筛选条件的索引号;参数Title指定对话框的标题;参数ButtonText用于Macintosh机。
FileDialog对象
FileDialog对象允许通过指定InitialFileName属性的值来指定起始目录,但是只能在Excel 2002或更高版本的Excel中使用FileDialog对象。
提示:因为FileDialog对象是在Excel 2002中才引入的,因此只能在Excel 2002及以后的Excel版本中使用该对象。
下面的过程显示一个对话框,允许用户选中某个目录,然后使用MsgBox函数显示出所选目录的名称,或者显示取消的信息。

Sub GetAFolder()
    '仅适用于Excel 2002或更高版本
    With Application.FileDialog(msoFileDialogFilePicker)
        .InitialFileName = Application.DefaultFilePath & "\"
        .Title = "Please select a location for the backup"
        .Show
        If .SelectedItems.Count = 0 Then
            MsgBox "Canceled"
        Else
            MsgBox .SelectedItems(1)
        End If
    End With
End Sub

本例中,使用Excel的默认文件路径作为起始目录。
FileSearch对象
(以下来源于VBA帮助)
代表“文件”菜单中“打开”对话框的功能。使用FileSearch属性可以返回FileSearch 对象。

本示例创建一个FoundFiles对象,该对象代表My Documents文件夹中的所有Microsoft Excel工作簿。

With Application.FileSearch
    .LookIn = "c:\my documents"
    .FileType = msoFileTypeExcelWorkbooks
    .Execute
End With

以下示例可实现:查找指定文件并显示找到的文件数及每个找到的文件的名称。

With Application.FileSearch
    If .Execute() > 0 Then
        MsgBox "There were " & .FoundFiles.Count & _
            " file(s) found."
        For i = 1 To .FoundFiles.Count
            MsgBox .FoundFiles(i)
        Next i
    Else
        MsgBox "There were no files found."
    End If
End With

使用NewSearch方法可以将搜索条件重新设置为默认设置。所有属性值在每次搜索过程后仍然保持不变,用NewSearch方法可有选择地为下一次文件搜索过程设置属性,而无须手动重新设置原先的属性值。以下示例可实现:在开始新的一轮搜索之前将搜索条件重新设置为默认设置。

With Application.FileSearch
    .NewSearch
    .LookIn = "C:\My Documents"
    .SearchSubFolders = True
    .FileName = "Run"
    .MatchTextExactly = True
    .FileType = msoFileTypeAllFiles
End With

FileName属性
返回或设置文件搜索过程中要查找的文件名。文件名中可以包含 *(星号)或 ?(问号)通配符。问号通配符可以匹配任意一个单个字符。如键入“gr?y”可以匹配“gray”和“grey”。星号通配符可以匹配任意个字符。如键入“*.txt”可以查找到所有带.TXT扩展名的文件。String 类型,可读写。
本示例搜索My Documents文件夹中所有以“cmd”开头的文件,并显示查找到的每一个文件的名称和位置。

Set fs = Application.FileSearch
With fs
    .LookIn = "C:\My Documents"
    .FileName = "cmd*.*"
    If .Execute > 0 Then
        MsgBox "There were " & .FoundFiles.Count & _
            " file(s) found."
        For i = 1 To .FoundFiles.Count
            MsgBox .FoundFiles(i)
        Next i
    Else
        MsgBox "There were no files found."
    End If
End With

FileType属性
返回或设置文件搜索过程中要查找的文件类型。可读写,MsoFileType常量。MsoFileType 可为以下 MsoFileType 常量之一:msoFileTypeAllFiles、msoFileTypeBinders、msoFileTypeCalendarItem、msoFileTypeContactItem、msoFileTypeCustom、msoFileTypeDatabases、msoFileTypeDataConnectionFiles、msoFileTypeDesignerFiles、msoFileTypeDocumentImagingFiles、msoFileTypeExcelWorkbooks、msoFileTypeJournalItem、msoFileTypeMailItem、msoFileTypeNoteItem、msoFileTypeOfficeFiles、msoFileTypeOutlookItems、msoFileTypePhotoDrawFiles、msoFileTypePowerPointPresentations、msoFileTypeProjectFiles、msoFileTypePublisherFiles、msoFileTypeTaskItem、msoFileTypeTemplates、msoFileTypeVisioFiles、msoFileTypeWebPages。
msoFileTypeWordDocuments常量msoFileTypeOfficeFiles包含以下任意扩展名的文件:*.doc、*.xls、*.ppt、*.pps、* obd、*.mdb、*.mpd、*.dot、*.xlt、*.pot、*.obt、*.htm 或 *.html。
本示例可实现的功能为:搜索位于“My Documents”文件夹中的所有“活页夹”文件,然后在消息框中显示找到的每个文件的文件名及其所在位置。

Set fs = Application.FileSearch
With fs
    .LookIn = "C:\My Documents"
    .FileType = msoFileTypeBinders
    If .Execute > 0 Then
        MsgBox "There were " & .FoundFiles.Count & _
            " Binder file(s) found."
        For i = 1 To .FoundFiles.Count
            MsgBox .FoundFiles(i)
        Next i
    Else
        MsgBox "There were no Binder files found."
    End If
End With

FileTypes 属性
返回一个FileTypes集合。
本示例搜索 C:\ 驱动器上的所有 HTML 和 Microsoft Excel 文件。

Sub SearchForFiles()
    'Declare a variable to act as a generic counter.
    Dim lngCount As Long
    'Use a With...End With block to reference the
    'FileSearch object.
    With Application.FileSearch
        'Clear all the parameters of the previous searches.
        'This method doesn't clear the LookIn property or
        'the SearchFolders collection.
        .NewSearch
        'Setting the FileType property clears the
        'FileTypes collection and sets the first
        'item in the collection to the file type
        'defined by the FileType property.
        .FileType = msoFileTypeWebPages
        'Add a second item to the FileTypes collection.
        .FileTypes.Add msoFileTypeExcelWorkbooks
        'Display the number of FileTypes objects in the collection.
        MsgBox "You are about to search for " & .FileTypes.Count & _
            " file types."
        'Set up the search to look in all subfolders on the C:\ drive.
        .LookIn = "C:\"
        .SearchSubFolders = True
        'Execute the search and test to see if any files
        'were found.
        If .Execute <> 0 Then
            'Display the number of files found.
            MsgBox "Files found: " & .FoundFiles.Count
            'Loop through the list of found files and
            'display the path of each one in a message box.
            For lngCount = 1 To .FoundFiles.Count
                If MsgBox(.FoundFiles.Item(lngCount), vbOKCancel, _
                    "Found files") = vbCancel Then
                    'Break out of the loop
                    lngCount = .FoundFiles.Count
                End If
            Next lngCount
        Else
            MsgBox "No files found."
        End If
    End With
End Sub

FileTypes 集合
msoFileType类型值的集合,决定FileSearch对象的Execute方法返回的文件类型。使用FileSearch对象的FileTypes属性返回一个FileTypes集合。例如:

Set ft = Application.FileSearch.FileTypes

注释:FileSearch对象的FileType属性清除FileTypes集合,并将集合中的第一项设置为FileType属性定义的文件类型。
所有搜索只有一个FileTypes集合,因此在执行搜索之前清除FileTypes集合很重要,除非希望搜索上次搜索的文件类型。清除集合的最简便方法是将FileType属性设置为要搜索的第一种文件类型。还可以使用Remove方法删除单个类型。要确定集合中每项的文件类型,请使用Item方法返回msoFileType值。
本示例在FileTypes集合中循环,并删除所有非Microsoft Word或Microsoft Excel文件的文件类型(通常,清除FileTypes集合再从头开始更简便)。

Sub RemoveFileTypeFromCollection()
    'Define an integer to use as a counter
    'when iterating through the FileTypes collection.
    Dim intFileIndex As Integer
    'Use a With...End With block to reference the FileSearch object.
    With Application.FileSearch
        'Loop through all of the items in the FileTypes collection.
        intFileIndex = 1
        Do While intFileIndex <= .FileTypes.Count
            Select Case .FileTypes.Item(intFileIndex)
                Case msoFileTypeWordDocuments, msoFileTypeExcelWorkbooks
                Case Else
                    'If the file type isn't a Microsoft Word or
                    'Microsoft Excel file, remove it.
                    .FileTypes.Remove intFileIndex
                    'Decrement the counter so that no file types are missed.
                    intFileIndex = intFileIndex - 1
            End Select
            'Increment the counter to test the next file type.
            intFileIndex = intFileIndex + 1
        Loop
    End With
End Sub

FoundFiles 属性
返回一个FoundFiles对象,该对象包括一次查找操作中找到的所有文件的文件名。只读。本示例可实现的功能为:逐个查看找到的文件列表中的每个文件,并显示各文件的路径。

With Application.FileSearch
    For i = 1 To .FoundFiles.Count
        MsgBox .FoundFiles(i)
    Next i
End With

LastModified 属性
返回或设置一个表示指定文件自上次修改和保存以来的时间量的常量。 默认值为msoLastModifiedAnyTime。MsoLastModified类型,可读写。
MsoLastModified可为下列MsoLastModified常量之一:msoLastModifiedAnyTime、msoLastModifiedLastMonth、msoLastModifiedLastWeek、msoLastModifiedThisMonth、msoLastModifiedThisWeek、msoLastModifiedToday、msoLastModifiedYesterday。
本示例可实现的功能为:为文件查找过程设置选项。该查找过程返回的是“C:\My Documents”文件夹或其子文件夹中,昨天修改过的文件。

Set fs = Application.FileSearch
With fs
    .LookIn = "C:\My Documents"
    .SearchSubFolders = True
    .LastModified = msoLastModifiedYesterday
End With

LookIn 属性
返回或设置在指定的文件搜索过程中要搜索的文件夹。String类型,可读写。
MatchAllWordForms 属性
如果文件查找范围扩展到在文件正文或文件属性中出现的指定单词的所有形式,则返回True。Boolean类型,可读写。
说明 该属性只有在安装并注册文件“Mswds_en.lex”后才有效。注意:在“典型”安装过程中不会安装该文件。
本示例可实现的功能为:返回所有在文件正文或文件属性中包含单词“run”、“running”、“runs”或“ran”的文件。TextOrProperty 属性设置需匹配的单词,并将查找范围限制在文件正文或文件属性中。

With Application.FileSearch
    .NewSearch
    .LookIn = "C:\My Documents"
    .SearchSubFolders = True
    .TextOrProperty = "run"
    .MatchAllWordForms = True
    .FileType = msoFileTypeAllFiles
End With

MatchTextExactly 属性
如果仅查找这样的文件,其文件正文中或文件属性中包括指定单词或短语的完全匹配形式,则返回True。Boolean类型,可读写。
本示例可实现的功能为:搜索“C:\My Documents”文件夹并返回所有在文件正文或文件属性中包含单词“Run”的文件。

With Application.FileSearch
    .NewSearch
    .LookIn = "C:\My Documents"
    .TextOrProperty = "Run"
    .MatchTextExactly = True
    .FileType = msoFileTypeAllFiles
End With

PropertyTests 属性
返回一个PropertyTests集合,该集合代表一个文件查找过程的所有搜索条件。只读。
本示例可实现的功能为:显示属性测试集合中第一个属性测试过程的所有搜索条件。

With Application.FileSearch.PropertyTests(1)
    myString = "This is the search criteria: " _
      & " The name is: " & .Name & ". The condition is: " _
      & .Condition
    If .Value <> "" Then
        myString = myString & ". The value is: " & .Value
        If .SecondValue <> "" Then
            myString = myString _
            & ". The second value is: " _
            & .SecondValue & ", and the connector is" _
            & .Connector
        End If
    End If
    MsgBox myString
End With

PropertyTests 集合对象
代表一个文件搜索条件。搜索条件列在“查找”对话框中(单击“文件”菜单中的“打开”命令,然后单击“查找”按钮)。PropertyTest对象是PropertyTests集合中的成员。
用PropertyTests属性可返回一个PropertyTests对象。以下示例显示查找单个文件的“查找”的搜索条件数。

Application.FileSearch.PropertyTests.Count

用Add方法向PropertyTests集合中添加一个新的PropertyTest对象。以下示例向搜索条件中添加两个属性测试。第一个条件指定查找任意类型的文件,第二个条件指定该文件应是在1996年1月1日至1996年6月30日之间修改的。然后,在消息框中显示找到的文件数和每个文件的名称。

Set fs = Application.FileSearch
fs.NewSearch
With fs.PropertyTests
    .Add Name:="Files of Type", _
        Condition:=msoConditionFileTypeAllFiles, _
        Connector:=msoConnectorOr
    .Add Name:="Last Modified", _
        Condition:=msoConditionAnytimeBetween, _
        Value:="1/1/96", SecondValue:="6/1/96", _
        Connector:=msoConnectorAnd
End With
If fs.Execute() > 0 Then
    MsgBox "There were " & fs.FoundFiles.Count & _
        " file(s) found."
        For i = 1 To fs.FoundFiles.Count
            MsgBox fs.FoundFiles(i)
        Next i
Else
        MsgBox "There were no files found."
End If

使用PropertyTests(index)可返回一个PropertyTest对象;此处index是该对象的索引号。
SearchFolders 属性
返回SearchFolders集合。本示例显示SearchFolders集合中ScopeFolder对象的当前数量。请参阅SearchFolders集合的主题获得详细示例。

MsgBox "Number of ScopeFolder objects in the SearchFolders collection: " & _
    Application.FileSearch.SearchFolders.Count

SearchFolders 集合
ScopeFolder对象的集合,这些对象确定调用FileSearch对象的Execute方法时搜索的文件夹。
使用FileSearch对象的SearchFolders属性返回SearchFolders集合,例如:

Set sfs = Application.FileSearch.SearchFolders

对于每个应用程序只有一个SearchFolders集合。集合的内容在调用它的代码执行结束后保持不变。因此,清除集合很重要,除非要在搜索中包括上一次搜索的文件夹。
可以使用SearchFolders集合的Add方法向SearchFolders集合中添加ScopeFolder对象,但是使用要添加的ScopeFolder对象的AddToSearchFolders方法更为简便,因为对于所有搜索只有一个SearchFolders集合。
SearchFolders集合可视为对FileSearch对象的LookIn属性的补充。二者均指定搜索的文件夹并在执行搜索时使用。但是,如果只希望使用LookIn属性,应确保SearchFolders集合为空。相反,如果只希望使用SearchFolders集合,请在Execute方法之前将LookIn属性设置为SearchFolders集合第一个成员的路径。
本示例搜索本地计算机上每个名为”1033″的文件夹,查找所有HTML和Microsoft Excel文件。本示例使用SearchFolders集合、SearchScopes集合和ScopeFolders集合。本示例由两个例程组成。SearchEveryFolder例程为要运行的例程。OutputPaths例程独立于主例程,因为它将递归调用自身以浏览本地计算机的整个目录结构。

Sub SearchEveryFolder()
    'Declare variables that reference a
    'SearchScope and a ScopeFolder object.
    Dim ss As SearchScope
    Dim sf As ScopeFolder
    'Declare a variable to act as a generic counter.
    Dim lngCount As Long
    'Use a With...End With block to reference the
    'FileSearch object.
    With Application.FileSearch
        'Clear all the parameters of the previous searches.
        'This method doesn't clear the LookIn property or
        'the SearchFolders collection.
        .NewSearch
        'Specify the type of file for which to search.
        'Use the FileType property to specify the first type
        'and then add additional types to the FileTypes collection.
        .FileType = msoFileTypeWebPages
        .FileTypes.Add msoFileTypeExcelWorkbooks
        'Clear the SearchFolder collection by
        'looping through each ScopeFolder object
        'and removing it.
        For lngCount = 1 To .SearchFolders.Count
            .SearchFolders.Remove lngCount
        Next lngCount
        'Loop through the SearchScopes collection to find
        'the scope in which you want to search. In this
        'case the scope is the local machine.
        For Each ss In .SearchScopes
            Select Case ss.Type
                Case msoSearchInMyComputer
                    'Loop through each ScopeFolder in
                    'the ScopeFolders collection of the
                    'SearchScope object.
                    For Each sf In ss.ScopeFolder.ScopeFolders
                        'Call a function that loops through all
                        'of the subfolders of the root ScopeFolder.
                        'This function adds any folders named "1033" to the
                        'SearchFolders collection.
                        Call OutputPaths(sf.ScopeFolders, "1033")
                    Next sf
                Case Else
            End Select
        Next ss
        'Test to see if any ScopeFolders collections were added to
        'the SearchFolders collection.
        If .SearchFolders.Count > 0 Then
            'Set the LookIn property to the path of
            'the first ScopeFolder object in the SearchFolders
            'collection. This is here so that any previous
            'setting of the LookIn property doesn't affect
            'the search.
            .LookIn = .SearchFolders.Item(1).Path
            'Execute the search and test to see if any files
            'were found.
            If .Execute <> 0 Then
                'Display the number of files found.
                MsgBox "Files found: " & .FoundFiles.Count
                'Loop through the list of found files and
                'display the path of each one in a message box.
                For lngCount = 1 To .FoundFiles.Count
                    If MsgBox(.FoundFiles.Item(lngCount), vbOKCancel, _
                        "Found files") = vbCancel Then
                       'Break out of the loop
                        lngCount = .FoundFiles.Count
                    End If
                Next lngCount
            End If
        End If
    End With
End Sub
'This subroutine loops through all of the ScopeFolders collections
'in a given ScopeFolders collection. It adds any folder
'that has the same name as the value of strFolder
'to the SearchFolders collection.
Sub OutputPaths(ByVal sfs As ScopeFolders, _
    ByRef strFolder As String)
    'Declare a variable as a ScopeFolder object
    Dim sf As ScopeFolder
    'Loop through each ScopeFolder object in the
    'ScopeFolders collection.
    For Each sf In sfs
        'Test to see if the folder name of the ScopeFolder
        'matches the value of strFolder. Use LCase to ensure
        'that case does not affect the match.
        If LCase(sf.Name) = LCase(strFolder) Then
            'Add the ScopeFolder to the SearchFolders collection.
            sf.AddToSearchFolders
        End If
        'Include a DoEvents call because there is the potential for this
        'loop to last a long time. The DoEvents call allows this process to
        'continue handling events.
        DoEvents
        'Test to see if the ScopeFolders collection in the
        'current ScopeFolder is empty. If it isn't empty, then
        'that means that the current ScopeFolder object contains subfolders.
        If sf.ScopeFolders.Count > 0 Then
            'This subroutine recursively calls itself so that
            'it can add the subfolders of the current ScopeFolder object
            'to the SearchFolders collection.
            Call OutputPaths(sf.ScopeFolders, strFolder)
        End If
    Next sf
End Sub

SearchScopes 属性
返回SearchScopes集合。本示例显示SearchScopes集合中所有当前可用的SearchScope对象。

Sub DisplayAvailableScopes()
    'Declare a variable that references a
    'SearchScope object.
    Dim ss As SearchScope
    'Use a With...End With block to reference the
    'FileSearch object.
    With Application.FileSearch
        'Loop through the SearchScopes collection
        For Each ss In .SearchScopes
            Select Case ss.Type
                Case msoSearchInMyComputer
                    MsgBox "My Computer is an available search scope."
                Case msoSearchInMyNetworkPlaces
                    MsgBox "My Network Places is an available search scope."
                Case msoSearchInOutlook
                    MsgBox "Outlook is an available search scope."
                Case msoSearchInCustom
                    MsgBox "A custom search scope is available."
                Case Else
                    MsgBox "Can't determine search scope."
            End Select
        Next ss
    End With
End Sub

SearchScopes 集合
SearchScope对象的集合。
使用FileSearch对象的SearchScopes属性返回SearchScopes集合,例如:

Dim sss As SearchScopes
Set sss = Application.FileSearch.SearchScopes

不能向SearchScopes集合中添加或从中删除SearchScope对象。
SearchSubFolders 属性
如果搜索范围包括LookIn属性指定的文件夹中的所有子文件夹,则返回True。Boolean类型,可读写。
TextOrProperty 属性
返回或设置在查找文件的过程中要搜索的单词或短语,它们可位于一个文件的正文或文件属性中。该单词或短语可包含 *(星号)或 ?(问号)通配符。String类型,可读写。
用问号通配符可匹配任意单个字符。例如,键入“gr?y”可找到符合如下条件的所有文件,即文件中至少有一处出现单词“gray”或“grey”。
用星号通配符可匹配任意数目的字符。例如,键入“San*”可找到符合如下条件的所有文件,即文件中至少有一处出现以“San”开头的单词。
本示例可实现的功能为:搜索“C:\My Documents”文件夹及其子文件夹,并返回所有这样的文件,该文件在文件正文或文件属性中包含以“San”开头的单词。TextOrProperty属性设置要查找的单词,并将搜索范围限制在文件正文或文件属性中。

With Application.FileSearch
    .NewSearch
    .LookIn = "C:\My Documents"
    .SearchSubFolders = True
    .TextOrProperty = "San*"
    .FileType = msoFileTypeAllFiles
End With

Execute 方法
开始对指定文件的搜索。返回一个Long类型,如果没有找到文件,则返回零(0),如果找到一个或多个文件,则返回一个正数。

expression.Execute(SortBy, SortOrder, AlwaysAccurate)

其中,expression必需。该表达式返回一个 FileSearch 对象。
参数SortBy,MsoSortBy 类型,可选。该方法用于对返回的文件进行排序。MsoSortBy 可以为下列 MsoSortBy 常量之一。 msoSortByFileName 默认值、msoSortByFileType、msoSortByLastModified、msoSortByNone、msoSortBySize。
参数SortOrder,MsoSortOrder类型,可选。表明所返回文件的排序顺序。
参数MsoSortOrder,可以为下列 MsoSortOrder 常量之一。 msoSortOrderAscending,默认值、msoSortOrderDescending。
参数AlwaysAccurate,Boolean类型,可选。设置为True使文件搜索包括上次更新文件索引以来添加、修改或删除的文件。默认值为True。
本示例在My Documents文件夹中搜索以扩展名 “.doc” 结尾的所有文件,然后显示找到的每个文件的位置和名称。本示例还以字母升序排序返回的文件名称。

Set fs = Application.FileSearch
With fs
    .LookIn = "C:\My Documents"
    .FileName = "*.doc"
    If .Execute(SortBy:=msoSortByFileName, _
            SortOrder:=msoSortOrderAscending) > 0 Then
        MsgBox "There were " & .FoundFiles.Count & _
            " file(s) found."
        For i = 1 To .FoundFiles.Count
            MsgBox .FoundFiles(i)
        Next i
    Else
        MsgBox "There were no files found."
    End If
End With

NewSearch 方法
将所有搜索条件重置为默认设置。搜索条件的设置在应用程序的一个会话中将保持不变。每次更改搜索条件时可用此方法。此方法不会重新设置LookIn属性的值。
本示例可实现的功能为:在开始新一轮搜索过程之前用NewSearch方法重新设置默认的搜索条件。

With Application.FileSearch
    .NewSearch
    .LookIn = "C:\My Documents"
    .SearchSubFolders = True
    .FileName = "run"
    .TextOrProperty = "San*"
    .MatchAllWordForms = True
    .FileType = msoFileTypeAllFiles
    If .Execute() > 0 Then
        MsgBox "There were " & .FoundFiles.Count & _
        " file(s) found."
        For i = 1 To .FoundFiles.Count
            MsgBox .FoundFiles(i)
        Next i
    Else
        MsgBox "There were no files found."
    End If
End With

RefreshScopes 方法
刷新当前可用ScopeFolder对象的列表。下面的示例将显示“我的电脑”C:\ 驱动器上所有当前可用的ScopeFolder对象,并说明在对文件夹列表进行更改时需要使用RefreshScopes方法。

Sub TestRefreshScopesMethod()
' Displays what happens before and after the RefreshScopes
' method is called when a new folder is added to the list
' of scope folders.
    ' List before the folder is created.
    Call ListFolderNames
    ' Create a new folder on the C:\ drive in My Computer.
    ' An error will occur if this folder already exists.
    MkDir Path:="C:\Delete_After_Using"
    ' List after the folder is created.
    ' The newly-created folder does not appear in the list.
    Call ListFolderNames
    ' Refresh the list of folders.
    Application.FileSearch.RefreshScopes
    ' The newly-created folder now appears in the list.
    Call ListFolderNames
End Sub
Sub ListFolderNames()
    Dim i As Integer
    Dim strResults As String
    ' Loop through all the top-level folder names on the C:\ drive
    ' in My Computer and report the results.
    ' .SearchScopes.Item(1) = "My Computer"
    ' .ScopeFolders.Item(2) = "C:\"
    With Application.FileSearch.SearchScopes.Item(1). _
        ScopeFolder.ScopeFolders.Item(2)
        For i = 1 To .ScopeFolders.Count
            strResults = strResults & .ScopeFolders. _
                Item(i).Name & vbCrLf
        Next i
        MsgBox "Folder Names on C:\...." & vbCrLf & strResults
    End With
End Sub

相关文章