VBA每日一练(9),VBA如何统计文件夹内的文件数量,文件名,以及按类型统计,按是否有内容统计

您所在的位置:网站首页 怎么批量统计文件夹里的页数 VBA每日一练(9),VBA如何统计文件夹内的文件数量,文件名,以及按类型统计,按是否有内容统计

VBA每日一练(9),VBA如何统计文件夹内的文件数量,文件名,以及按类型统计,按是否有内容统计

2024-07-12 11:24| 来源: 网络整理| 查看: 265

1 界定问题

我发现我现在入门阶段,读题经常偏题

这个问题,我觉得可以细化下  

统计文件夹内, 所有文件个数,filecount?统计文件夹内,某种类型的文件个数统计文件夹内, 所有文件名,这不有点像 dir吗?统计文件夹内,所有非空文件的文件个数统计文件夹内,所有某后缀名的非空文件的文件个数统计文件夹内,所有非空文件的文件名

 

2 不用fso 用VBA的 文件操作语句   代码1 正确的代码 Option Explicit Sub richardliu1() Dim path1, path2, path3 Dim fd1, f1, f2 Dim k, j path1 = "C:\Users\Administrator\Desktop\test1" path2 = "*.*" path3 = "*.txt" k = 1 j = 1 fd1 = Dir(path1, vbDirectory) f1 = Dir(path1 & "\" & path2) ' f1.name只有对象才可以这么使用,由于 f1不是对象,不能这样引用对象的方法的语法 'dir返回的的不是 文件file对象,而只是文件名,VB默认都是文本字符串 '只有fso相关的是对象 Debug.Print "fd1是" & fd1 Debug.Print "f1是" & f1 Open path1 & "\" & f1 For Input As #1 '这里如果只写 open f1 因为路径不完整会报错找不到 Do While Len(f1) 0 f1 = Dir 'Debug.Print k 'Debug.Print f1 k = k + 1 Loop Close #1 Debug.Print k f2 = Dir(path1 & "\" & path3) '特别注意,这个dir不能写在 f1的循环前,否则会影响 *.*的判断循环 Debug.Print "f2是" & f2 Open path1 & "\" & f2 For Input As #2 Do While Len(f2) 0 f2 = Dir 'Debug.Print j 'Debug.Print f2 j = j + 1 Loop Close #2 Debug.Print j End Sub

 

代码1-1:纯粹的错误例子,而且无法运行---放这后面再看看自己为啥这么挫把 Sub robinlee1() '错误例子,我写的第一个,太烂了,思路混乱 Dim x1, str1 'x1 = FreeFile str1 = 999 '不知道这么启动循环是不是太山寨,行不行 '*.*这样可以查找所有文件吧? '如果只是取文件名呢,怎么取 '这是取非空文件,不是取文件数,或文件名把 k = 0 Do While Len(str1) Open "C:\Users\Administrator\Desktop" & "\*.*" For Input As #1 Input #1, str1 Debug.Print str1 k = k + 1 Close #1 Loop End Sub Sub robinlee1() '先统计*.*的个数 '我的想法是,先dir进这个文件夹,或直接找到这个文件夹,逐一loop所有文件 '文件名不为空那就是有文件 '然后把文件名,文件内容取出来 do while len() Open "C:\Users\Administrator\Desktop" For Input As #1 name1 = #1.name Close #1 Loop End Sub  

 

不用fso也可以 Sub jack007() x1 = FileCount("C:\Users\Administrator\Desktop\test1\") Debug.Print x1 End Sub Function FileCount(cPath As String) As Integer cFile = Dir(cPath & "*.txt") Do While cFile "" FileCount = FileCount + 1 cFile = Dir Loop Debug.Print FileCount End Function

 

 

2 用FSO的 代码2:用 fso写很简单 Sub jackma22() Dim fso Dim f1 Set fso = CreateObject("scripting.filesystemobject") Set f1 = fso.getfolder("C:\Users\Administrator\Desktop\test1") Debug.Print f1.Name Debug.Print f1.Files.Count End Sub

如果还有子文件夹多层呢?

 

http://club.excelhome.net/thread-959260-1-1.html

Function FileCount(cPath As String) as Integer

    cFile=Dir(cPath & "*.*")

    Do While cFile""

        FileCount=FileCount+1

        cFile=Dir

    Loop

End Function

 

Private Sub CommandButton1_Click()    fp = "d:\DWG\*.*"    fn = Dir(fp)    i = 1    [b2:b65536].ClearContents    Do While fn ""        i = i + 1        Cells(i, 2).Value = fn        fn = Dir    LoopEnd Sub


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3