【问题标题】:Unable to search/loop through subfolders无法搜索/循环浏览子文件夹
【发布时间】:2018-08-12 18:09:48
【问题描述】:

谁能帮助我为什么不能从子文件夹中提取文件?

如果文件位于主文件夹中,我的代码将定位并附加到电子邮件中,但如果文件位于子文件夹中,则不会。

代码示例:

Set obMail = Outlook.CreateItem(olMailItem)
With obMail
    .to = "email@comapny.com"
    .Subject = "O/S Blanace"
    .BodyFormat = olFormatPlain
    .Body = "Please see attached files"

    iRow = 24 'initialize row index from 24
    Do While Cells(iRow, 1) <> Empty

        'picking up file name from column A
        pFile = Dir(dPath & "\*" & Cells(iRow, 1) & "*")

        'checking for file exist in a folder and if its a pdf file
        If pFile <> "" And Right(pFile, 3) = "pdf" Then
            .Attachments.Add (dPath & "\" & pFile)
        End If

        'go to next file listed on the A column
        iRow = iRow + 1
    Loop

    .Send
End With

【问题讨论】:

  • 从单元格 A26 向下显示“电子邮件”表的内容
  • 欢迎来到Stack Overflow -- 请edit 您的问题仅包含最小、完整和可验证:在提供重现问题所需的所有部分(包括数据)和发布之前,使用尽可能少的代码测试您发布的确切代码和数据,以确保它重现问题(使用您发布的数据)。拥有产生问题所需的一切(没有额外的东西)可以让其他人更容易帮助你。 更多信息:“minimal reproducible example & “help center”。
  • @ashleedawg 谢谢并缩短我的代码长度。
  • @PraSon - 确认:A列 您的工作表有一个您需要附加的文件名列表,这些文件位于dPath unknown 子文件夹,对吗?或者是否有另一列包含文件的完整路径?
  • @PraSon - 不客气。这个地方需要一些时间来适应,但一旦你习惯了,它就是一个令人难以置信的数据来源,所有的许多规则和“礼仪”都开始变得有意义。例如,嘘!不要再感谢我了! 信不信由你 这也违反了规则——请参阅this...(实际上,这更适用于“噪音”,例如 posts 但 cmets 并不是什么大不了的事。)我个人对此表示赞赏。 :-)

标签: vba excel


【解决方案1】:

Dir 函数不会遍历子文件夹。它遍历你给它的路径,而不是树结构。它在调用时也会重置,因此递归调用不是一种选择。

所以如果你通过"C:\Test\"你可以使用它来遍历Test;如果单元格包含"C:\Test\NextTest\",您可以使用它来迭代NextTest

可以做的是使用Collection 来保存每个目录并以这种方式递归探索。

有关如何执行此操作的示例,请参阅How To Traverse Subdirectories with Dir 中的以下内容

Sub TraversePath(path As String)
    Dim currentPath As String, directory As Variant
    Dim dirCollection As Collection
    Set dirCollection = New Collection

    currentPath = Dir(path, vbDirectory)

    'Explore current directory
    Do Until currentPath = vbNullString
        Debug.Print currentPath
        If Left(currentPath, 1) <> "." And _
            (GetAttr(path & currentPath) And vbDirectory) = vbDirectory Then
            dirCollection.Add currentPath
        End If
        currentPath = Dir()
    Loop

    'Explore subsequent directories
    For Each directory In dirCollection
        Debug.Print "---SubDirectory: " & directory & "---"
        TraversePath path & directory & "\"
    Next directory
End Sub


Sub Test()
    TraversePath "C:\Root\"
End Sub

您可以轻松地调整它以适应您的目的。

【讨论】:

  • 我已经完成了这部分,它确实通过了测试,并在即时窗口中打印了文件夹和子文件夹中的所有文件名。但是我在应用我当前的代码时遇到了一些困难。 :( 不知道如何将其应用于我上面的邮件合并代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-07
相关资源
最近更新 更多