Excel2007中用DIR函數批量獲取指定目錄下所有文件名
由于 Excel2007 及 Excel 版本都取消了對 Application 對象的 FileSearch 方法的支持,所以在 Excel2007 版本以后不能用 FileSearch 來批量獲取指定目錄下的所有文件名了,雖然少了 FileSearch 但還可以用內置的 Dir 函數。代碼如下:
Sub listfile()””””””””””””””””””””””’‘ Dir函數批量獲取指定目錄下所有文件名和內容 ‘‘ ‘””””””””””””””””””””””’Dim mypath As String, nm As StringDim theSh As ObjectDim theFolder As ObjectDim i As Integer
Application.ScreenUpdating = FalseOn Error Resume Next‘設置搜索路徑Set theSh = CreateObject("shell.application")Set theFolder = theSh.BrowseForFolder(0, "", 0, "")If Not theFolder Is Nothing Thenmypath = theFolder.Items.Item.PathEnd If‘//////////////搜索開始////////////////
nm = Dir(mypath & "*.*") ‘第一次使用dir,必須指定pathname參數,返回符合條件的第1個文件名i = 1Range("a1") = nm ‘單元格A1返回找到的第一個文件名 Do While nm <> ""nm = Dir ‘再次調用不需要pathname參數Range("a" & i + 1) = nmi = i + 1LoopApplication.ScreenUpdating = True
End Sub