Excel2007中用DIR函数批量获取指定目录下所有文件名
由于 Excel2007 及 Excel2010 版本都取消了对 Application 对象的 FileSearch 方法的支持,所以在 Excel2007 版本以后不能用 FileSearch 来批量获取指定目录下的所有文件名了,虽然少了 FileSearch 但还可以用内置的 Dir 函数。代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | Sub listfile() ''''''''''''''''''''''''''''''''''''''''''''' ' 宏由 www.pootor.com 录制,时间: 2009-12-24 ' ' 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 |
很有用,谢啦!