国产一级a片免费看高清,亚洲熟女中文字幕在线视频,黄三级高清在线播放,免费黄色视频在线看

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

開通VIP
使用VBA操作文件(1):使用Excel對話框

本專題主要講述使用VBA操作文件和文件夾的相關知識,盡量不涉及對文件中具體內容的操作。如何操作文件中具體內容的知識,將在后續(xù)內容外部數(shù)據(jù)操作中作詳細介紹。
Excel VBA提供了一些方法和對象,能夠調用Excel內置對話框來進行文件操作。
 GetOpenFilename方法
使用GetOpenFilename方法能夠獲得有效的文件名,包括該文件的完整路徑。此時,將顯示標準的“打開”對話框,但并不真正打開指定的文件,而是返回包含用戶所選文件的文件名和路徑的字符串。其語法如下:

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

所有參數(shù)均可選。其中,參數(shù)FileFilter代表指定文件篩選條件的字符串,即確定出現(xiàn)在在“打開”對話框中“文件類型”下拉列表中的內容,由文件篩選字符串和通配符表示的文件篩選規(guī)則說明組成,其中每一部分和每一對都用逗號隔開。如果省略,則該參數(shù)的的默認值為:

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

該字符串的第一部分(All Files (*.*))是顯示在“文件類型”下拉列表中的文本,第二部分(*.*)實際上確定要顯示哪些文件。
下面的指令將一個字符串賦值給名為Filt的變量,然后可以用作GetOpenFilename方法的參數(shù)FileFilter的值。

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

此時,“打開”對話框允許用戶從5種文件類型中選擇。
提示:使用換行符將長語句分成多行,有助于代碼閱讀。
參數(shù)FilterIndex代表默認的文件篩選條件的索引號,用于指定在“文件類型”框中顯示的文件類型。
參數(shù)Title代表對話框的標題,如果省略該參數(shù),則標題為“打開”。
參數(shù)ButtonText只用于Macintosh機。
參數(shù)MultiSelect用于指定是否能夠選擇多個文件名,如果為True則能夠選中多個文件名,所有這些文件將返回到一個數(shù)組中。默認值為False。

Sub GetImportFileName()    Dim Filt As String    Dim FilterIndex As Integer    Dim Title As String    Dim FileName As Variant     '創(chuàng)建文件篩選列表    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 " & FileNameEnd Sub

下面的代碼與上述代碼類似,區(qū)別在于用戶可以按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     '創(chuàng)建文件篩選列表    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 & MsgEnd Sub

此時,變量FileName是一個數(shù)組。該過程通過判斷FileName變量是否是數(shù)組,檢測用戶是否單擊了“取消”按鈕。如果沒有單擊“取消”按鈕,那么結果至少是由一個元素組成的數(shù)組。
GetSaveAsFilename方法
GetSaveAsFilename方法與GetOpenFilename方法類似,但它顯示的是“另存為”對話框,允許用戶選擇或者指定某文件。該方法返回一個文件名及其路徑,但不會發(fā)生任何動作。其語法為:

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

所有參數(shù)均為可選參數(shù)。其中,參數(shù)InitialFilename指定希望使用的文件名稱;參數(shù)FileFilter是指定文件篩選條件的字符串;FilterIndex指定默認文件篩選條件的索引號;參數(shù)Title指定對話框的標題;參數(shù)ButtonText用于Macintosh機。
FileDialog對象
FileDialog對象允許通過指定InitialFileName屬性的值來指定起始目錄,但是只能在Excel 2002或更高版本的Excel中使用FileDialog對象。
提示:因為FileDialog對象是在Excel 2002中才引入的,因此只能在Excel 2002及以后的Excel版本中使用該對象。
下面的過程顯示一個對話框,允許用戶選中某個目錄,然后使用MsgBox函數(shù)顯示出所選目錄的名稱,或者顯示取消的信息。

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 WithEnd Sub

本例中,使用Excel的默認文件路徑作為起始目錄。
FileSearch對象
(以下來源于VBA幫助)
代表“文件”菜單中“打開”對話框的功能。使用FileSearch屬性可以返回FileSearch 對象。


本示例創(chuàng)建一個FoundFiles對象,該對象代表My Documents文件夾中的所有Microsoft Excel工作簿。

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

以下示例可實現(xiàn):查找指定文件并顯示找到的文件數(shù)及每個找到的文件的名稱。

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 IfEnd With

使用NewSearch方法可以將搜索條件重新設置為默認設置。所有屬性值在每次搜索過程后仍然保持不變,用NewSearch方法可有選擇地為下一次文件搜索過程設置屬性,而無須手動重新設置原先的屬性值。以下示例可實現(xiàn):在開始新的一輪搜索之前將搜索條件重新設置為默認設置。

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

FileName屬性
返回或設置文件搜索過程中要查找的文件名。文件名中可以包含 *(星號)或 ?(問號)通配符。問號通配符可以匹配任意一個單個字符。如鍵入“gr?y”可以匹配“gray”和“grey”。星號通配符可以匹配任意個字符。如鍵入“*.txt”可以查找到所有帶.TXT擴展名的文件。String 類型,可讀寫。
本示例搜索My Documents文件夾中所有以“cmd”開頭的文件,并顯示查找到的每一個文件的名稱和位置。

Set fs = Application.FileSearchWith 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 IfEnd With

FileType屬性
返回或設置文件搜索過程中要查找的文件類型??勺x寫,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。
本示例可實現(xiàn)的功能為:搜索位于“My Documents”文件夾中的所有“活頁夾”文件,然后在消息框中顯示找到的每個文件的文件名及其所在位置。

Set fs = Application.FileSearchWith 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 IfEnd 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 WithEnd Sub

FileTypes 集合
msoFileType類型值的集合,決定FileSearch對象的Execute方法返回的文件類型。使用FileSearch對象的FileTypes屬性返回一個FileTypes集合。例如:

Set ft = Application.FileSearch.FileTypes

注釋:FileSearch對象的FileType屬性清除FileTypes集合,并將集合中的第一項設置為FileType屬性定義的文件類型。
所有搜索只有一個FileTypes集合,因此在執(zhí)行搜索之前清除FileTypes集合很重要,除非希望搜索上次搜索的文件類型。清除集合的最簡便方法是將FileType屬性設置為要搜索的第一種文件類型。還可以使用Remove方法刪除單個類型。要確定集合中每項的文件類型,請使用Item方法返回msoFileType值。
本示例在FileTypes集合中循環(huán),并刪除所有非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 WithEnd Sub

FoundFiles 屬性
返回一個FoundFiles對象,該對象包括一次查找操作中找到的所有文件的文件名。只讀。本示例可實現(xiàn)的功能為:逐個查看找到的文件列表中的每個文件,并顯示各文件的路徑。

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

LastModified 屬性
返回或設置一個表示指定文件自上次修改和保存以來的時間量的常量。 默認值為msoLastModifiedAnyTime。MsoLastModified類型,可讀寫。
MsoLastModified可為下列MsoLastModified常量之一:msoLastModifiedAnyTime、msoLastModifiedLastMonth、msoLastModifiedLastWeek、msoLastModifiedThisMonth、msoLastModifiedThisWeek、msoLastModifiedToday、msoLastModifiedYesterday。
本示例可實現(xiàn)的功能為:為文件查找過程設置選項。該查找過程返回的是“C:\My Documents”文件夾或其子文件夾中,昨天修改過的文件。

Set fs = Application.FileSearchWith fs    .LookIn = "C:\My Documents"    .SearchSubFolders = True    .LastModified = msoLastModifiedYesterdayEnd With

LookIn 屬性
返回或設置在指定的文件搜索過程中要搜索的文件夾。String類型,可讀寫。
MatchAllWordForms 屬性
如果文件查找范圍擴展到在文件正文或文件屬性中出現(xiàn)的指定單詞的所有形式,則返回True。Boolean類型,可讀寫。
說明 該屬性只有在安裝并注冊文件“Mswds_en.lex”后才有效。注意:在“典型”安裝過程中不會安裝該文件。
本示例可實現(xiàn)的功能為:返回所有在文件正文或文件屬性中包含單詞“run”、“running”、“runs”或“ran”的文件。TextOrProperty 屬性設置需匹配的單詞,并將查找范圍限制在文件正文或文件屬性中。

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

MatchTextExactly 屬性
如果僅查找這樣的文件,其文件正文中或文件屬性中包括指定單詞或短語的完全匹配形式,則返回True。Boolean類型,可讀寫。
本示例可實現(xiàn)的功能為:搜索“C:\My Documents”文件夾并返回所有在文件正文或文件屬性中包含單詞“Run”的文件。

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

PropertyTests 屬性
返回一個PropertyTests集合,該集合代表一個文件查找過程的所有搜索條件。只讀。
本示例可實現(xiàn)的功能為:顯示屬性測試集合中第一個屬性測試過程的所有搜索條件。

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 myStringEnd With

PropertyTests 集合對象
代表一個文件搜索條件。搜索條件列在“查找”對話框中(單擊“文件”菜單中的“打開”命令,然后單擊“查找”按鈕)。PropertyTest對象是PropertyTests集合中的成員。
用PropertyTests屬性可返回一個PropertyTests對象。以下示例顯示查找單個文件的“查找”的搜索條件數(shù)。

Application.FileSearch.PropertyTests.Count

用Add方法向PropertyTests集合中添加一個新的PropertyTest對象。以下示例向搜索條件中添加兩個屬性測試。第一個條件指定查找任意類型的文件,第二個條件指定該文件應是在1996年1月1日至1996年6月30日之間修改的。然后,在消息框中顯示找到的文件數(shù)和每個文件的名稱。

Set fs = Application.FileSearchfs.NewSearchWith 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:=msoConnectorAndEnd WithIf 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 iElse        MsgBox "There were no files found."End If

使用PropertyTests(index)可返回一個PropertyTest對象;此處index是該對象的索引號。
SearchFolders 屬性
返回SearchFolders集合。本示例顯示SearchFolders集合中ScopeFolder對象的當前數(shù)量。請參閱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集合。集合的內容在調用它的代碼執(zhí)行結束后保持不變。因此,清除集合很重要,除非要在搜索中包括上一次搜索的文件夾。
可以使用SearchFolders集合的Add方法向SearchFolders集合中添加ScopeFolder對象,但是使用要添加的ScopeFolder對象的AddToSearchFolders方法更為簡便,因為對于所有搜索只有一個SearchFolders集合。
SearchFolders集合可視為對FileSearch對象的LookIn屬性的補充。二者均指定搜索的文件夾并在執(zhí)行搜索時使用。但是,如果只希望使用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 WithEnd 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 sfEnd 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 WithEnd Sub

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

Dim sss As SearchScopesSet sss = Application.FileSearch.SearchScopes

不能向SearchScopes集合中添加或從中刪除SearchScope對象。
SearchSubFolders 屬性
如果搜索范圍包括LookIn屬性指定的文件夾中的所有子文件夾,則返回True。Boolean類型,可讀寫。
TextOrProperty 屬性
返回或設置在查找文件的過程中要搜索的單詞或短語,它們可位于一個文件的正文或文件屬性中。該單詞或短語可包含 *(星號)或 ?(問號)通配符。String類型,可讀寫。
用問號通配符可匹配任意單個字符。例如,鍵入“gr?y”可找到符合如下條件的所有文件,即文件中至少有一處出現(xiàn)單詞“gray”或“grey”。
用星號通配符可匹配任意數(shù)目的字符。例如,鍵入“San*”可找到符合如下條件的所有文件,即文件中至少有一處出現(xiàn)以“San”開頭的單詞。
本示例可實現(xiàn)的功能為:搜索“C:\My Documents”文件夾及其子文件夾,并返回所有這樣的文件,該文件在文件正文或文件屬性中包含以“San”開頭的單詞。TextOrProperty屬性設置要查找的單詞,并將搜索范圍限制在文件正文或文件屬性中。

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

Execute 方法
開始對指定文件的搜索。返回一個Long類型,如果沒有找到文件,則返回零(0),如果找到一個或多個文件,則返回一個正數(shù)。

expression.Execute(SortBy, SortOrder, AlwaysAccurate)

其中,expression必需。該表達式返回一個 FileSearch 對象。
參數(shù)SortBy,MsoSortBy 類型,可選。該方法用于對返回的文件進行排序。MsoSortBy 可以為下列 MsoSortBy 常量之一。 msoSortByFileName 默認值、msoSortByFileType、msoSortByLastModified、msoSortByNone、msoSortBySize。
參數(shù)SortOrder,MsoSortOrder類型,可選。表明所返回文件的排序順序。
參數(shù)MsoSortOrder,可以為下列 MsoSortOrder 常量之一。 msoSortOrderAscending,默認值、msoSortOrderDescending。
參數(shù)AlwaysAccurate,Boolean類型,可選。設置為True使文件搜索包括上次更新文件索引以來添加、修改或刪除的文件。默認值為True。
本示例在My Documents文件夾中搜索以擴展名 “.doc” 結尾的所有文件,然后顯示找到的每個文件的位置和名稱。本示例還以字母升序排序返回的文件名稱。

Set fs = Application.FileSearchWith 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 IfEnd With

NewSearch 方法
將所有搜索條件重置為默認設置。搜索條件的設置在應用程序的一個會話中將保持不變。每次更改搜索條件時可用此方法。此方法不會重新設置LookIn屬性的值。
本示例可實現(xiàn)的功能為:在開始新一輪搜索過程之前用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 IfEnd 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 ListFolderNamesEnd SubSub 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 WithEnd Sub
 
本站僅提供存儲服務,所有內容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權內容,請點擊舉報。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
3,多工作簿匯總(FileSearch)
Office VBA教程:Execute方法
VBA遍歷所有文件夾的兩種方法(filesearch和FileSystemObject)
VBA文件夾遍歷
VBA 打開選擇文件和目標文件夾對話框
Excel應用程序對象(Application對象)及其常用方法基本操作應用示例 - 灰太...
更多類似文章 >>
生活服務
分享 收藏 導長圖 關注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權!
如果VIP功能使用有故障,
可點擊這里聯(lián)系客服!

聯(lián)系客服