使用excel 2010 vba列出目录中的特定文件类型

时间:2016-08-22 14:51:02

标签: excel-vba excel-2010 vba excel

excel 2010 vba中,我尝试列出特定目录中的所有.txt个文件,并在消息提示中显示它们。我希望以下是一个好的开始,但不确定。谢谢 :)。

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 个答案:

答案 0 :(得分:1)

我能想到的两种方式:

第一个没有循环,对于大文件夹来说可能更快:

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

无论哪种方式 - 记得将\放在文件路径的末尾。