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