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

End Sub

office办公软件入门基础教程 » Excel2007中用DIR函数批量获取指定目录下所有文件名

本文链接:【Excel2007中用DIR函数批量获取指定目录下所有文件名】https://www.officeapi.cn/35422.html

OFFICE,天天学一点,进步多一点

联系我们