Excel2007中用DIR函数批量获取指定目录下所有文件名

由于 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
【Excel2007中用DIR函数批量获取指定目录下所有文件名】End Sub

    推荐阅读