【VBA】【增强版】【收藏备用】遍历文件夹内所有文件模块V5
2018-12-03 12:34:30


N次修改了,此模块应该比较健壮吧,特点:
1、可遍历目录下所有文件
2、可筛选文件类型,可限定文件名关键词
3、遍历目录(文件夹)允许存在小数点.
4、一步到位,不用编写2次循环(即先遍历出目录,再遍历文件)
Sub searchFile()' ---------------遍历文件夹内所有文件-----------------------------FileType = '.txt' '查找文件类型FileKeyword = 'svr' '进一步限定文件范围,当然也可以继续添加限定条件'对话框方式选择路径Dim fd As FileDialogSet fd = Application.FileDialog(msoFileDialogFolderPicker)If fd.Show = -1 ThensFolderPath = fd.SelectedItems(1)Set fd = NothingElseSet fd = NothingExit SubEnd IfDim file() As String, retFile() As String, fullPath$Dim i%, k%, t%, f$i = 1: k = 1: t = 1ReDim file(1 To i)file(1) = sFolderPath & '\''相对而言i父目录,k为对应子目录Do Until i > kDebug.Print 'file(' & i & ')=' & file(i)f = Dir(file(i), vbDirectory)Do Until f = ''Debug.Print 'f1=' & fIf InStr(f, FileType) > 0 And InStr(f, FileKeyword) > 0 ThenReDim Preserve retFile(1 To t)' 把遍历得到的文件存放到retFile(t)中retFile(t) = file(i) & ft = t + 1ElseIf f <> '.' And f <> '..' ThenfullPath = file(i) & f & '\'If FileFolderExists(fullPath) Thenk = k + 1ReDim Preserve file(1 To k)file(k) = fullPathEnd IfEnd Iff = DirLoopi = i + 1LoopEnd SubFunction FileFolderExists(strFullPath As String) As BooleanDim fsoSet fso = CreateObject('Scripting.FileSystemObject')If fso.folderExists(strFullPath) Then FileFolderExists = TrueSet fso = NothingEnd Function
赞 (0)
