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

转贴自  http://www.excelperfect.com/2009/08/05/handlefileswithvba/

 

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

本专题主要讲述使用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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值