【问题标题】:Problem when chaining Do-While loops in Excel VBA在 Excel VBA 中链接 Do-While 循环时出现问题
【发布时间】:2022-01-10 14:36:02
【问题描述】:

我对 Excel VBA 中的代码有疑问,该代码应遍历所有(子)文件夹和每个文件夹中的所有 .jpg 文件。这是代码:

Sub list()
'
' list Macro
'
Dim folder
Dim path As String
path = "C:\Users\Lorian\Desktop\Example_jpegALL\"
folder = Dir(path, vbDirectory)

Do While folder <> ""

    Debug.Print folder
    
    Dim file
    Dim path2 As String
    path2 = path & folder & "\"
    file = Dir(path2 & "*.jpg")
    
    Do While file <> ""
    
        Debug.Print file
        file = Dir()
        
    Loop

    folder = Dir()
Loop

End Sub

调试工具告诉我错误来自“folder = Dir()”行,更具体地说,它是“运行时错误 5:无效的过程调用或参数”。我对此错误进行了研究,但没有任何帮助...

更新感谢上面的 cmets,我能够通过使用集合来更正代码:

Sub list()
'
' list Macro
'
Dim folder
Dim path As String
Dim Coll As New Collection
path = "C:\Users\Lorian\Desktop\Example_jpegALL\"
folder = Dir(path, vbDirectory)


    Do While folder <> ""
    
        Coll.Add folder
        folder = Dir()
        
    Loop



    Dim file
    Dim path2 As String
    
    For Each folder In Coll
    
    Debug.Print folder
    path2 = path & folder & "\"
    file = Dir(path2 & "*.jpg")
    
    Do While file <> ""
    
        Debug.Print file
        file = Dir()
        
    Loop

    Next
End Sub

但是我仍然有一个小错误,由于我无法理解的原因,输出还返回了我桌面上的 JPG 文件,例如这是它给我的输出(前两个文件来自我的桌面,其余的):

.
..
91cba94b061174b15ca65010e00edb03.jpg
holyshit.JPG
1
jpegsystems-home.jpg
JPEG_example_flower.jpg
2
jpegxt-home.jpg
3
happy_dog.jpg
images.jpg
téléchargement (1).jpg
téléchargement.jpg
PDF

【问题讨论】:

  • 只能有一个Dir-loop 处于活动状态。当您在内循环中发出命令file = Dir(path2 &amp; "*.jpg") 时,外循环的Dir 的信息就消失了。在开始“内部循环”之前存储外部Dir 的结果以获取文件夹列表,或者改用 FileSystemObject
  • @Tim Williams:您能分享一下建议的解决方案中... 的含义吗?
  • . 代表目录本身,.. 是父目录。在这种情况下,我们对这些项目不感兴趣。见superuser.com/questions/37449/what-are-and-in-a-directorystackoverflow.com/questions/5050525/…
  • 你想要只有一级子文件夹,还是子文件夹的子文件夹等?

标签: excel vba loops directory do-while


【解决方案1】:

像这样:

'
' list Macro
'
Sub list()
    Const FPATH As String = "C:\Users\twilliams\OneDrive - Theravance Biopharma\Desktop\pics\"
    Dim d, coll As New Collection, file, f, folder
    
    coll.Add FPATH 'add the root folder
    'check for subfolders (one level only)
    d = Dir(FPATH, vbDirectory)
    Do While d <> ""
        If (GetAttr(FPATH & d) And vbDirectory) <> 0 Then
            If d <> "." And d <> ".." Then coll.Add FPATH & d
        End If
        d = Dir()
    Loop
    
    For Each folder In coll
        Debug.Print "Checking folder"; folder
        file = Dir(folder & "\*.jpg")
        Do While file <> ""
            Debug.Print , file
            file = Dir()
        Loop
    Next
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-16
    • 2011-09-21
    • 1970-01-01
    • 2015-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多