|
本帖最后由 wpxxsyzx 于 2011-9-1 16:13 编辑
论坛最近要求遍历文件夹或文件夹下的文件帖子比较多,每次都要编写一样的查找的代码,把它做成函数,以后方便使用。
有的要求递归遍历所有子文件夹,正好用字典实现。
'MuLu是要查找的文件夹,如:"F:\VBA\pdf\Excel2007VBA"
'LeiXing是要查找的文件类型,如:*.xls,a?*.txt等,如果省略该参数,函数实现的是查找文件夹功能
'LeiXing参数不省略时:1、Zi为true时搜索所有子文件夹下符合要求的文件。2、Zi为false时仅搜索参数MuLu下符合要求的文件
'LeiXing参数省略时: 1、Zi为true时搜索参数MuLu下所有子文件。2、Zi为false时仅搜索参数MuLu下的文件夹
'函数的返回值是一个一维数组,可视具体情况使用
Public Function ListFile(MuLu As String, Zi As Boolean, Optional LeiXing As String = "")
Dim MyFile As String, ms As String
Dim arr, brr, x
Dim i As Integer
Set d = CreateObject("Scripting.Dictionary")
If Left(MuLu, 1) <> "\" Then MuLu = MuLu & "\"
d.Add MuLu, ""
i = 0
Do While i < d.Count
brr = d.keys
MyFile = Dir(brr(i), vbDirectory)
Do While MyFile <> ""
If MyFile <> "." And MyFile <> ".." Then
If (GetAttr(brr(i) & MyFile) And vbDirectory) = vbDirectory Then d.Add (brr(i) & MyFile & "\"), ""
End If
MyFile = Dir
Loop
If Zi = False Then Exit Do
i = i + 1
Loop
If LeiXing = "" Then
ListFile = Application.Transpose(d.keys)
Else
For Each x In d.keys
MyFile = Dir(x & LeiXing)
Do While MyFile <> ""
ms = ms & x & MyFile & ","
MyFile = Dir
Loop
If Zi = False Then Exit For
Next
If ms = "" Then ms = "没有符合要求的文件,"
ListFile = Application.Transpose(Split(ms, ","))
End If
End Function
测试函数:
Public Sub a()
Dim a
a = ListFile("F:\VBA\pdf\Excel2007VBA", True, "*.xls")
Range("a1").Resize(UBound(a), 1) = a
End Sub
枚举文件的函数.rar
(12.47 KB, 下载次数: 2049)
|
评分
-
4
查看全部评分
-
|