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

1 界定问题

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

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

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

 

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

 

  1. Private Sub CommandButton1_Click()
  2.     fp = "d:\DWG\*.*"
  3.     fn = Dir(fp)
  4.     i = 1
  5.     [b2:b65536].ClearContents
  6.     Do While fn <> ""
  7.         i = i + 1
  8.         Cells(i, 2).Value = fn
  9.         fn = Dir
  10.     Loop
  11. End Sub
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值