|
本帖最后由 yxbaju 于 2019-1-20 12:37 编辑
为了方便,自定义了一个函数,如下所示:- Function all_paths(Parent_path, Optional Extension = "", Optional Recur = False)
- '''返回指定目录下所有文件列表(没有返回Null),可指定扩展名,可指定是否搜索子文件夹'''
- Dim fsObject, Folder, subFolders, subFolder, File, ex$, rec As Boolean
- Static Paths_Array(), n&
- ex = Extension
- rec = Recur
- Set fsObject = CreateObject("Scripting.FileSystemObject")
- Set Folder = fsObject.GetFolder(Parent_path)
- For Each File In Folder.Files
- If ex <> "" Then
- If fsObject.GetExtensionName(File) = Extension Then
- n = n + 1
- ReDim Preserve Paths_Array(1 To n)
- Paths_Array(n) = File
- End If
- Else
- n = n + 1
- ReDim Preserve Paths_Array(1 To n)
- Paths_Array(n) = File
- End If
- Next
- If rec = True Then
- Set subFolders = Folder.subFolders
- For Each subFolder In subFolders
- Call all_paths(subFolder, ex, rec)
- Next
- End If
- If n = 0 Then
- all_paths = Null
- Else
- all_paths = Paths_Array
- End If
- End Function
复制代码
当我使用如下代码进行测试时,list列表不能初始化,会不停重复增加之前的文件,特在此请教如何让本例的list每次结束后会变成一个空变量
- Sub test()
- Dim list, f
- list = all_paths(ThisWorkbook.Path, "txt", True)
- For Each f In list
- Debug.Print f
- Next
- End Sub
复制代码
|
|