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