vba中dir函数使用心得


Dir[(pathname[,attributes])]

构建测试环境如下:

 

一、测试在dir函数中使用通配符来查找多个文件,在VBE中输入代码如下:

Sub ListFiles()
Dim strPath As String, strTmp As String
strPath = "c:\test\"
strTmp = Dir(strPath & "*.txt")

Do While strTmp <> ""
Debug.Print strPath & strTmp
strTmp = Dir
Loop
End Sub
本意为查找所有txt文档,得到结果如下:

c:\test\vba.txt
c:\test\新建文本文档.txtd
c:\test\新建文本文档 (2).txt

程序运行结果中不但包括txt文档,还包含txtd文件。

二、测试attributes参数,代码如下:

Sub ListSubFolder()
Dim strPath As String, strTmp As String
strPath = "c:\test\"
strTmp = Dir(strPath & "vb*", vbDirectory)
Do While strTmp <> ""
Debug.Print strPath & strTmp
strTmp = Dir
Loop
End Sub
本意为查找VB开头的文件夹,程序运行结果为:

c:\test\vba
c:\test\vba.txt

结果中不但包含了VBA文件夹,还包含VBA.txt文件。

三、感想及小结

1.dir函数是完全按字节匹配pathname参数,而不是按类型。

2.attributes参数是包含关系,而不是独有关系。

3.如只想获得文件夹,需使用条件判断语句。例,if getattr(strPath) and vbDirectory then .
————————————————
版权声明:本文为CSDN博主「zjz1228」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zjz1228/article/details/104629321


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM