兩個我能想到的辦法:
先不循環,並能更快的大文件夾:
Public Sub Test()
Dim vFiles As Variant
Dim x As Long
Dim sMsg As String
vFiles = EnumerateFiles("C:\aCGH\", "txt", False)
For x = LBound(vFiles) To UBound(vFiles)
sMsg = sMsg & vFiles(x) & Chr(13)
Next x
MsgBox sMsg
End Sub
Public Function EnumerateFiles(sDirectory As String, _
Optional sFileSpec As String = "*", _
Optional InclSubFolders As Boolean = True) As Variant
EnumerateFiles = Filter(Split(CreateObject("WScript.Shell").Exec _
("CMD /C DIR """ & sDirectory & "*." & sFileSpec & """ " & _
IIf(InclSubFolders, "/S ", "") & "/B /A:-D").StdOut.ReadAll, vbCrLf), ".")
End Function
第二種方式基本上和你一樣:
Sub Test1()
Dim cFiles As Collection
Dim vFile As Variant
Dim sMsg As String
Set cFiles = New Collection
EnumerateFiles1 "C:\aCGH\", "*.txt", cFiles
For Each vFile In cFiles
sMsg = sMsg & vFile & Chr(13)
Next vFile
MsgBox sMsg
End Sub
Sub EnumerateFiles1(ByVal sDirectory As String, _
ByVal sFileSpec As String, _
ByRef cCollection As Collection)
Dim sTemp As String
sTemp = Dir$(sDirectory & sFileSpec)
Do While Len(sTemp) > 0
cCollection.Add sTemp
sTemp = Dir$
Loop
End Sub
使用您的代碼將是:
Sub Test3()
Dim sMsg As String
' LIST ALL TEXT FILES IN REPORT DIRECTORY '
Const strFolder As String = "C:\aCGH\"
Const strPattern As String = "*.txt"
Dim strFile As String
strFile = Dir(strFolder & strPattern, vbNormal)
Do While Len(strFile) > 0
sMsg = sMsg & strFile & Chr(13)
strFile = Dir
Loop
MsgBox sMsg
End Sub
無論哪種方式 - 記得把\
上的文件路徑的結尾。
非常感謝:) – Chris