VBA 获得文件夹下的所有文件(包括子文件夹)列表,输出为getfilelist数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Function getfilelist(path As String) As Variant
'返回文件夹的所有文件,输出位getfilelist数组
Dim ifolder As Folder
Dim ifile As file
Dim filelist As New ArrayList
 
Set root = os.GetFolder(path)
 
For Each ifile In root.Files
    filelist.Add ifile.Name
Next
 
For Each ifolder In root.SubFolders
    For Each ifile In ifolder.Files
        filelist.Add ifile.Name
    Next
Next
 
getfilelist = filelist.ToArray
 
End Function 

  

其他Sub程序可以直接调用此函数;例如

1
2
3
4
5
Sub fds()
Dim c As Variant
c = getfilelist("C:\Users\xyz\software")
Debug.Print "文件夹下共有" & UBound(c) & "个文件"
Debug.Print "第一个文件名是:" & c(0)

 

 

 

 

 本方法使用到Arraylist。

=======================================================

其实,不要说VBA没有好的列表,数组方法。VBA本身直接对接Excel表格,可以把数据直接写到excel单元格,这就是非常强大的“数组或者列表”,而且很直观,可以把“数组,列表”显现出来。真正做到可视化编程。这是其他编程语言做不到的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Sub dfasdf()
 
Dim root As Folder
Dim wjj As Folder  'wjj文件夹
Dim wj As file        'wj文件
 
ActiveSheet.UsedRange.Clear
 
i = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
 
Set root = fso.GetFolder("C:\Users\uuxyz\software")
 
For Each wj In root.Files
    Range("A" & i) = wj.Name
    i = i + 1
Next
 
For Each wjj In root.SubFolders
    For Each wj In wjj.Files
    Range("A" & i) = wj.Name
    i = i + 1
    Next
Next
 
End Sub   

  

 

posted @   uuxyz  阅读(2812)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
联系我
点击右上角即可分享
微信分享提示