“Do While”代码不会遍历目录 - 只能看到一个文件

时间:2017-10-19 20:58:27

标签: excel-vba vba excel

我的Do While循环用于遍历目录中的所有文件,但它只能看到一个文件。

For x = 2 To ActiveWorkbook.Sheets("NumNF").Range("a1")

    numb_nota = ThisWorkbook.Sheets("controle").Range("C" & x).Value
    Name = "Nota Fiscal P&G número " & Left(numb_nota, 9) & ".PDF"

    Directory = "C:\Users\andrade.br\Documents\Test\"
    Filename = Dir(Directory & "*.PDF")

    Do While Filename <> ""

        If Name = Filename Then

            .Attachments.Add Directory & Filename
        End If

    Loop
Next

我做错了什么?

1 个答案:

答案 0 :(得分:2)

您的循环只能看到一个文件,因为您只执行Dir一次(获取第一个文件)。要使循环工作,您需要设置Filename = Dir()以检索下一个文件。

For x = 2 To ActiveWorkbook.Sheets("NumNF").Range("a1")

    numb_nota = ThisWorkbook.Sheets("controle").Range("C" & x).Value
    Name = "Nota Fiscal P&G número " & Left(numb_nota, 9) & ".PDF"

    Directory = "C:\Users\andrade.br\Documents\Test\"
    Filename = Dir(Directory & "*.PDF")

    Do While Filename <> ""

        If Name = Filename Then

            .Attachments.Add Directory & Filename
        End If
        Filename = Dir() ' retrieve the next file name
    Loop
Next

但是,因为您只处理单个文件,所以代码可以大大简化为:

Directory = "C:\Users\andrade.br\Documents\Test\"
For x = 2 To ActiveWorkbook.Sheets("NumNF").Range("a1")
    numb_nota = ThisWorkbook.Sheets("controle").Range("C" & x).Value
    Filename = Directory & "Nota Fiscal P&G número " & Left(numb_nota, 9) & ".PDF"

    If Dir(Filename) <> "" Then
        .Attachments.Add Filename
    End If
Next