问题
In an excel 2010 vba
I am trying to list all .txt
files in a specific directory and display them in a message prompt. I hope the below is a good start, but not sure. Thank you :).
vba
' 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
Debug.Print strFile
strFile = Dir
Loop
MsgBox "The files are " + strFile
回答1:
Two ways I can think of:
The first doesn't loop and could be quicker for a large folder:
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
The second way is basically the same as yours:
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
Using your code it would be:
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
Either way - remember to put the \
on the end of the file path.
来源:https://stackoverflow.com/questions/39082641/list-specific-file-type-in-directory-using-excel-2010-vba