如何正确识别 VBA Dir Loop 中的文件?

How do I correctly identify file in VBA Dir Loop?

此处的目标是遍历包含数千个 .txt 文件的文件夹,并将有关每个文件的一些信息(从文本中)提取到电子表格中。

当我 运行 if 时,我得到 运行-time error '53' - File Not Found error at Line 21 (Open FileName For Input As #FileNum).

当我 运行 循环导入单个文件的文本(包括该行)时,它 运行 没问题。但是当我尝试添加外部循环以命令它循环遍历所有文件时,我得到了错误。我不确定如何解决它。

Sub TextDataLoop()
    Dim FilePath As String
    Dim Sh As Worksheet
    Dim FileName As String
    Dim FileNum As Integer
    Dim r As Long
    Dim Data As String
    Dim Txt As String
    
    FilePath = "I:\ArchivedCustomerOrders\"
    Set Sh = Worksheets("Sheet1")

    FileName = Dir(FilePath & "*.txt")
    FileNum = FreeFile
    r = 2
    
    Do While Right(FilePath, 3) > 0
        Open FileName For Input As #FileNum
        
        Do While Not EOF(FileNum)
            Line Input #FileNum, Data
            Txt = Txt & Join(Split(Data, vbTab), " ") & " "
        Loop
                
        Sh.Cells(r, 1).Value = FileName
        Sh.Cells(r, 2).Value = Trim(Mid(Txt, 95, 7))
        Sh.Cells(r, 3).Value = Trim(Mid(Txt, 122, 9))
        Sh.Cells(r, 4).Value = Trim(Mid(Txt, 991, 5))
        
        Close #FileNum
        
        r = r + 1    
    Loop
End Sub

您只有文件 NAME - 如果您想打开该文件,请使用包含路径的完全限定名称

Do While Right(FilePath, 3) > 0
    Open FilePath & FileName For Input As #FileNum

这里有几个问题:
a) Dir returns 只有文件名,没有完整路径。您需要指定路径和文件名:

Open FilePath & FileName For Input As #FileNum

b) 当你想遍历所有文件时,你需要在循环结束时发出一个 Dir(不带参数)以便你可以继续下一个文件。

c) 您在 Do-While 条件中检查了 FilePath-Variable,但它永远不会改变。您需要检查变量 FileName.

 FileName = Dir(FilePath & "*.txt")
 Do While FileName <> ""        ' Loop while there are still files.
    Open FilePath & FileName For Input As #FileNum
    ... (do your file handling here) ...
    Close #FileNum
    
    r = r + 1    
    FileName = Dir   ' Get the name of the next file
Loop