标签:
‘这里我要说明一下,在Excel2010中FileSearch已经失效,CreateObject("Scripting.FileSystemObject")也有问题
‘获取一个目录下所有的文件
Public Function getFiles(folderPath As String) As Variant Dim tempFileName As String
‘Variant表示任意类型 Dim fileNames() As Variant
‘记录fileNames的总长度 Dim fileNameLen As Integer
‘记录fileNames的当前最大的索引 Dim index As Integer
‘从字符串最右边截取长度为1的子串 tempFileName = Right(folderPath, 1)
‘判断子串是否为路径分割符 If tempFileName <> "\" And tempFileName <> "/" Then folderPath = folderPath & "\" End If folderPath = folderPath
‘获取目录下的所有文件,不过这里tempFileName只能取得第一个,Dir后的$符号表示取得的是字符串,vbHidden表示获取包含隐藏文件的文件(普通文件以及隐藏的文件,不包括系统文件) tempFileName = Dir$(folderPath & "*", vbHidden)
‘重新为数组分配内存 ReDim fileNames(100) As Variant fileNameLen = 99 index = 0
‘判断数组名是否为空 Do While tempFileName <> ""
‘FileDateTime函数计算出文件的日期 fileNames(index) = tempFileName & " " & FileDateTime(folderPath & tempFileName) index = index + 1 tempFileName = Dir If index >= fileNameLen Then
‘Preserve关键字的作用是避免数组中的数据被清空,若不加该关键字,内存重新分配不会保留数组中的原有数据 ReDim Preserve fileNames(fileNameLen + 21) As Variant
‘UBound表示取得数组的上边界索引,LBound表示取得数组的下边界索引 fileNameLen = UBound(fileNames) - LBound(fileNames) End If Loop getFiles = fileNames End Function
标签:
原文地址:http://www.cnblogs.com/XuJianShen/p/4260074.html